What is the best way to share data between a WPF window and its User Controls?

前端 未结 3 627
死守一世寂寞
死守一世寂寞 2021-01-05 09:46

WPF can be infuriating sometimes.

I have a fairly simple application that consists of a single main window that contains a tab control and several tabs. I did not l

相关标签:
3条回答
  • 2021-01-05 10:23

    You could put the settings object into a static property in a wrapper class (SettingsHolder in this example and reference it application wide via

    in XAML:

    {Binding SettingName, Source={x:Static local:SettingsHolder.Settings}}
    

    with local being the namespace your SettingsHolder class is in.

    in Code:

    var x = SettingsHolder.Settings.SettingName;
    SettingsHolder.Settings.SettingName = x;
    
    0 讨论(0)
  • 2021-01-05 10:39

    In the declaration of your user control you could just set the data context to the instance of the object that contains all the things you need to bind to!

    <someNamespace:EricsUserControl DataContext="{Binding InstanceOfBindingObject}"/>

    Then you can access the properties of that objects' instance within the user control as you normally would.

    0 讨论(0)
  • 2021-01-05 10:47

    What I do is use a Frame in the Tab and place a Page in the Frame. (but I think the same can apply with a User Control). The constructor only fires when the Page is created and you can control when the page is created and you can pass information in the constructor. A Page has more lifecycle events to tie into. I also use the Loaded event for building UI (it just fires once). If you bind the Page in XAML it will fire when you start the app and you cannot pass information. This is creating a page and showing it in a dialog but that page could be bound to a frame.

            NavigationWindow winSearchXML;
            using (new WaitCursor())
            {
                winSearchXML = new NavigationWindow();
                winSearchXML.Content = new PageSearchResultsXML(GabeLib.GetSearchXML(GabeLib.enumXMLtype.Flat));
            }
            winSearchXML.ShowDialog();
    

    I need to be honest that some times I get a life cycle on a page that I just don't understand. So take this with a grain of salt. But the point is you have the contructor and loaded events that might give you what you need.

    0 讨论(0)
提交回复
热议问题