Search code examples
c#wpfxamluser-controlswindow

Access Window property from UserControl child


I have a MainWindow with a TabControl. Each Tab is a UserControl existing in a different file.

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

These UserControls should act different depending on the access rights. The access rights (an int) are passed to the Main Window after the login screen via:

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

Now I have the access rights in the MainWindow.xaml.cs. But how can I access these access rights in the UserControls.


Solution

  • You could add a dependency property to each 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));
    }
    

    ...and bind it to a public property of the parent window in your XAML markup:

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

    How to: Implement a Dependency Property: https://msdn.microsoft.com/en-us/library/ms750428(v=vs.110).aspx

    Make sure that the window class exposes the access right(s) using a public property because you cannot bind to fields.

    The other option would be to get a reference to the parent window using the Window.GetWindow method in the code-behind of the UserControl once it has been loaded:

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