你可以依賴屬性添加到每個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));
}
...並將其綁定到父窗口的公共屬性在XAML標記:
<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.GetWindow
方法在UserControl
的代碼隱藏父窗口的引用:
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...
}
};
}
}
來源
2017-03-20 11:52:52
mm8
如何用靜態實例創建'UserManagement'類,然後讓你的'UserControl'和其他控件,類從這個實例中獲取'int'? –