简体   繁体   中英

MVVM Dependency Property and DataContext

I'm having issues figuring out something that's probably pretty stupid.

I have this xaml on a parent control for my user control:

<Map:LocationInformationControl FarmerID="{Binding SelectedFarmerID}"></Map:LocationInformationControl>

In the control that this xaml is on has the SelectedFarmerID property on it's viewmodel and all is fine there.

My LocationInformationControl is a custom control that I have this dependency property on:

       public static readonly DependencyProperty FarmerIDProperty = DependencyProperty.Register(
        "FarmerID", 
        typeof(int),
        typeof(LocationInformationControl), 
        new FrameworkPropertyMetadata(
            0, new PropertyChangedCallback(OnFarmerIDChanged)
            ));

    public int FarmerID
    {
        get 
        { 
            return (int)GetValue(FarmerIDProperty); 
        }
        set 
        { 
            SetValue(FarmerIDProperty, value); 
        }
    }

This is my On Property Changed Callback

    private static void OnFarmerIDChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {

    }

It fires fine, and everything is great. But when I hook up the view model to the custom control like this:

this.DataContext = new LocationInformationViewModel()

The property changed callback won't fire anymore. I'm assuming it's because I'm changing the data context of the control so it won't find FarmerID anymore. But is there anyway I can have a ViewModel set up like that and still have a dependency property on the same control?

Thanks, Aaron

It is a common mistake to set the DataContext of a UserControl to itself, or a view model as in your case, from inside that control . There are many beginner tutorials that show this, but that is simply because it is one of the quickest and easiest ways to get data into the UI in WPF. [Of course, there are exceptions.]

So instead of setting the DataContext to the view model internally and Binding to your UserControl properties from inside the control like this...:

<TextBlock Text="{Binding FarmerID}" />

... dont' set the DataContext and use the following RelativeSource Binding :

<TextBlock Text="{Binding FarmerID, RelativeSource={RelativeSource AncestorType={x:Type
YourLocalXmlNamespacePrefix:LocationInformationControl}}}" />

In this way, the Binding will look for the FarmerID in the LocationInformationControl control, no matter whether the DataContext is set or not. You can almost think of this as setting the DataContext , but for just this one Binding .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM