从 UserControl 子项访问 Window 属性

Access Window property from UserControl child

我有一个 MainWindow 和一个 TabControl。每个 Tab 都是一个存在于不同文件中的 UserControl。

...
<TabControl>
   <TabItem>
      <local:Tab1>
   </TabItem>
...
   <TabItem>
      <local:Tab2>
   </TabItem>
</TabControl>

这些用户控件应该根据访问权限的不同而有所不同。访问权限(一个整数)在登录屏幕后通过以下方式传递给 Main Window:

MainWindow mainWindow = new MainWindow(accessRights);
mainWindow.show();

现在我有 MainWindow.xaml.cs 的访问权限了。但是如何在 UserControls 中访问这些访问权限。

在创建 UserControl 实例时将 MainWindow 实例的引用传递给它们的构造函数。通过这样做,您可以访问 UserControls 代码中包含主窗体的 public 属性。

将此逻辑添加到您的用户控件:

MainWindow mw = (MainWindow)this.Parent;
accessRights = mw.accessRights;

这是逻辑,您可能需要更改上面的代码以匹配语法等。

您可以为每个 UserControl 添加依赖项 属性 class:

public class Tab1 : UserControl
{
    ...

    public Boolean HasAccess
    {
        get { return (Boolean)this.GetValue(HasAccessProperty); }
        set { this.SetValue(HasAccessProperty, value); }
    }
    public static readonly DependencyProperty HasAccessProperty = DependencyProperty.Register(
      "HasAccess", typeof(Boolean), typeof(Tab1), new PropertyMetadata(false));
}

...并将其绑定到 XAML 标记中父 window 的 public 属性:

<TabControl>
    <TabItem>
        <local:Tab1 HasAccess="{Binding Path=WindowProperty, RelativeSource={RelativeSource AncestorType=Window}}" />
    </TabItem>
    ...
</TabControl>

如何:实现依赖关系 属性: https://msdn.microsoft.com/en-us/library/ms750428(v=vs.110).aspx

确保 window class 使用 public 属性 公开访问权限,因为您无法绑定到字段。

另一种选择是在 UserControl 加载后使用 Window.GetWindow 方法在 UserControl 的代码隐藏中获取对父 window 的引用:

public partial class MyUserControl : UserControl
{
    public MyUserControl()
    {
        InitializeComponent();
        Loaded += (s, e) => 
        {
            MainWindow parentWindow = Window.GetWindow(this) as MainWindow;
            if(parentWindow != null)
            {
                //access property of the MainWindow class that exposes the access rights...
            }
        };
    }
}

尝试使用 Prism.Core 中的 EventAggregator,基本上你设置 Publish 方法,你传递你的 int 并在该用户控件中订阅该事件,事件将在你的情况下 Window 加载。

主要WindowViewModel

   public MainWindowViewModel( IEventAggregator eventAggregator)
    {
        eventAggregator.GetEvent<PassingIntToUserControlEvent>().Publish(HereGoesYourInt);
    }

UserControlViewModel

 public UserControlViewModel( IEventAggregator eventAggregator)
    {
        eventAggregator.GetEvent<PassingIntToUserControlEvent>().Subscribe(SomeMethodYouWantWithYourInt);
    }

设置 PassingIntToUserControlEvent 非常简单。

public class PassingIntToUserControlEvent : PubSubEvent<int>{}

准备开始。

该视频对 Prism 及其部分组件进行了基本介绍,其中之一是 EventAggregator。我发现它非常有用。希望能帮助到你。 https://www.youtube.com/watch?v=ZfBy2nfykqY