c# - 从 UserControl 子项访问 Window 属性

标签 c# wpf xaml user-controls window

我有一个带有 TabControl 的主窗口。每个 Tab 都是一个存在于不同文件中的 UserControl。

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

这些用户控件应该根据访问权限的不同而有所不同。访问权限(int)在登录屏幕后通过以下方式传递到主窗口:

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

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

最佳答案

您可以为每个 UserControl 类添加一个依赖属性:

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));
}

...并将其绑定(bind)到 XAML 标记中父窗口的公共(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

确保窗口类使用公共(public)属性公开访问权限,因为您无法绑定(bind)到字段。

另一种选择是在 UserControl 加载后使用 Window.GetWindow 方法获取对父窗口的引用:

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...
            }
        };
    }
}

关于c# - 从 UserControl 子项访问 Window 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42900950/

相关文章:

c# - 通过 TCP 发送长 XML

C#:尝试以编程方式设置我网站的 "ServerBindings"属性,不断崩溃

mysql - 使用 linq 从 DataTable 获取 bool 值

wpf - 摆脱WPF中的按钮边框?

c# - MVVM ItemsControl 简单绑定(bind)

xaml - 转换器无法将类型 'Windows.Foundation.String' 的值转换为类型 'ImageSource'

c# - 如何获得 - 0 表示四舍五入的小负数?

c# - EF Core,当我只有一个包含类型的字符串变量时,如何查询我的 DbContext?

c# - 绑定(bind)到 WPF 中的 TreeView

xaml - 有没有办法在另一个 XAML 文件中包含 XAML 文件?