繁体   English   中英

从主窗口进行内容控制中的访问控制

[英]Access control in content control from main window

我找到了从用户控件访问主窗口的方法:

  • 窗口parentWindow = Window.GetWindow(this);
  • DependencyObject parentWindow = VisualTreeHelper.GetParent(child);
  • Application.Current.MainWindow作为parentWindow;

我有一些疑问:

  1. 以上哪种方法最好?
  2. 如何从主窗口访问用户控件中的控件,以及在同一主窗口中从用户控件访问用户控件?

谢谢,跳过我的英语不好:)

在每种情况下, 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.MainWindowWindow.GetWindow(this) :不好,因为您破坏了常见的设计模式和规则(例如“原理依赖倒置”或MVVM)

在编写XAML转换器(直接与UI处理的元素)时,使用VisualTreeHelper有时会很有用。 在代码中不可取,因为您强烈依赖于xaml可视树。

如果要在MainWindowUserControl之间进行通信,并为其他程序集保留可重用的UserControl ,请向您的Usercontrol添加一个或多个依赖项属性 ,然后在Xaml中设置绑定。

如果您想要快速简便的测试应用程序,请确保Application.Current.MainWindow仍然是一个不错的选择。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM