[英]Access control in content control from main window
我找到了从用户控件访问主窗口的方法:
我有一些疑问:
谢谢,跳过我的英语不好:)
在每种情况下, Current.MainWindow
都是理想的选择,因为如果将UserControl
嵌入在另一个UserControl
,则仍然可以使用Current.MainWindow
遍历树。 所有方法都很好,这取决于用法和您要完成的工作。
访问UserControl
的控件(比如说TextBlock )。
TextBlock tb = FindVisualChildren<TextBlock>(usercontrol)
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
所建议的都不是“最佳”的:
Application.Current.MainWindow
或Window.GetWindow(this)
:不好,因为您破坏了常见的设计模式和规则(例如“原理依赖倒置”或MVVM)
在编写XAML转换器(直接与UI处理的元素)时,使用VisualTreeHelper
有时会很有用。 在代码中不可取,因为您强烈依赖于xaml可视树。
如果要在MainWindow
和UserControl
之间进行通信,并为其他程序集保留可重用的UserControl
,请向您的Usercontrol添加一个或多个依赖项属性 ,然后在Xaml中设置绑定。
如果您想要快速简便的测试应用程序,请确保Application.Current.MainWindow仍然是一个不错的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.