从 viewModel 获取控件
在我的 viewModel 中,我可以使用该窗口中有一个 FlowDocument 来获取与其关联的窗口
var windows = Application.Current.Windows;
for (var i = 0; i < windows.Count; i++)
{
if (windows[i].DataContext == this)
{
//
}
}
,我需要在我的 viewModel 中引用它,我知道我有时可以打破规则并编写一些代码隐藏,但因为我有窗口和此控件包含在该窗口中/子窗口中,我想我可以在没有任何代码隐藏的情况下完成它,有什么建议吗?
提前致谢
in my viewModel I can get the window associated with it using
var windows = Application.Current.Windows;
for (var i = 0; i < windows.Count; i++)
{
if (windows[i].DataContext == this)
{
//
}
}
there is a FlowDocument in this window that I need a reference to it here in my viewModel, I know I can sometime break the rules and write some code-behind , but since I have the window and this control is contained/child in/of this window I thought I can get it done without aany code-behind , any suggesstions ?
thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,如果您需要访问 ViewModel 中的 UI 元素,那么您就没有以正确的方式使用 MVVM。您应该考虑为此使用绑定(无论您正在做什么:-)
无论如何,您可以遍历可视化树来查找
Window
的后代。但是,FlowDocument
不在可视化树中,因为它是FrameworkContentElement
,因此VisualTreeHelper
将不起作用。您需要结合
VisualTreeHelper
和LogicalTreeHelper
:可以在此处找到此实现:通过视觉树查找元素这是它的一个稍微重写的版本,使用它就像
DependencyObjectExtensions.cs
First of, you're not using MVVM the right way if you need access to UI elements in the ViewModel. You should consider using bindings for this instead (whatever it is that you're doing:-)
Anyway, you can traverse the visual tree to find descendants of the
Window
. However theFlowDocument
isn't in the visual tree as it is aFrameworkContentElement
soVisualTreeHelper
won't work.You'll need to combine
VisualTreeHelper
andLogicalTreeHelper
: An implementation of this can be found here: Find Element By Visual TreeHere is a slightly rewritten version of it, use it like
DependencyObjectExtensions.cs