1

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;

...
user3854148
  • 49
  • 3
  • 9

1 Answers1

2

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}}}" />
Sheridan
  • 68,826
  • 24
  • 143
  • 183
  • Thanks for your reply. But what should I put if I want to bind a boolean varibale to datatrigger in the view? @Sheridan – user3854148 Jul 21 '14 at 13:34
  • A `Binding Path` is a `Binding Path` wherever you use it... so... still the same `Binding path`, but obviously using your *actual* property name. – Sheridan Jul 21 '14 at 13:39
  • @Sheridan Have you done this in practice? What you are describing is what I am attempting to do but have not found success. Your comments would be appreciated. [WPF: Custom DependencyProperty of UserControl is Null when DataContext is also set](http://stackoverflow.com/questions/27526778/wpf-custom-dependencyproperty-of-usercontrol-is-null-when-datacontext-is-also-s) – Derrick Moeller Dec 17 '14 at 18:41