Search code examples
wpfxamlbindingdatacontextdatatrigger

How do I bind wpf with specific datacontext from different classes?


Hi guys I am very new to WPF. I have two datacontexts in two different classes which are being binded by the elements in the View producing datatriggers, and one or the other wouldn't work as they cannot bind both datacontexts together. How do I bind xaml from two different classes using datacontext? Is there any alternative way could make it easier?

Class A

public Window1()
{
    InitializeComponent();
    Appointments = new Appointments();
    DataContext = Appointments;

}

Class B

private void FilterAppointments()
        {
            this.DataContext = this;

...

Solution

  • Firstly, you should never use DataContext = this; in any UserControl in a serious WPF Application. Secondly, you should look up the MVVM design pattern, which provides the idea of a view model for each view. Your Window or UserControl are the 'Views' and your view models are simply classes that contain all of the data properties that you need to display in your view.

    Therefore, you should declare a view model class (that implements the INotifyPropertyChanged interface) and put whatever you wanted to data bind into that. Finally, you should set that object as the DataContext property value. In that way, you'll have access to all the data that you need.

    Looking again at your question, it just occurred to me that you may have set the DataContext to this so that you could use properties that you declared in your Window or UserControl. If this is the case, then you should not set the DataContext to this, instead using a RelativeSource Binding to access the properties. That would free up the actual DataContext to be set however you like. Try this Binding within the Window or UserControl:

    <TextBlock Text="{Binding PropertyName, RelativeSource={RelativeSource 
        AncestorType={x:Type YourPrefix:YourWindowOrControl}}}" />