[英]Access control in content control from main window
I had found methods to access main window from usercontrol: 我找到了从用户控件访问主窗口的方法:
I have some questions: 我有一些疑问:
Thanks, Skip for my bad English :) 谢谢,跳过我的英语不好:)
Current.MainWindow
is ideal in every case because if a UserControl
is embedded inside another UserControl
, you can still use Current.MainWindow
traversing up the tree. 在每种情况下,
Current.MainWindow
都是理想的选择,因为如果将UserControl
嵌入在另一个UserControl
,则仍然可以使用Current.MainWindow
遍历树。 All the methods are fine and it all depends on usage and what you're trying to accomplish. 所有方法都很好,这取决于用法和您要完成的工作。
To access a control (lets say TextBlock ) inside a UserControl
. 访问
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;
}
}
}
}
None of the suggested is "best": 所建议的都不是“最佳”的:
Application.Current.MainWindow
or Window.GetWindow(this)
: not good since you're breaking with common design patterns and rules (like "principle dependency inversion" or MVVM) Application.Current.MainWindow
或Window.GetWindow(this)
:不好,因为您破坏了常见的设计模式和规则(例如“原理依赖倒置”或MVVM)
Using VisualTreeHelper
is sometimes useful when coding XAML Converters (such elements that directly deal with the UI). 在编写XAML转换器(直接与UI处理的元素)时,使用
VisualTreeHelper
有时会很有用。 Not preferrable in code since you're strongly depending on your xaml visual tree. 在代码中不可取,因为您强烈依赖于xaml可视树。
If you want to communicate between the MainWindow
and a UserControl
, keeping a resuable UserControl
for other assemblies, add one or more dependency properties to your Usercontrol, and set the binding in Xaml. 如果要在
MainWindow
和UserControl
之间进行通信,并为其他程序集保留可重用的UserControl
,请向您的Usercontrol添加一个或多个依赖项属性 ,然后在Xaml中设置绑定。
If you want quick and easy test apps, sure Application.Current.MainWindow is still a good choice. 如果您想要快速简便的测试应用程序,请确保Application.Current.MainWindow仍然是一个不错的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.