繁体   English   中英

MVVM依赖属性和DataContext

[英]MVVM Dependency Property and DataContext

我有问题找出可能非常愚蠢的东西。

我在用户控件的父控件上有这个xaml:

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

在这个xaml打开的控件中,它的viewmodel上有SelectedFarmerID属性,并且一切都很好。

我的LocationInformationControl是一个自定义控件,我有这个依赖属性:

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

这是我的On Property Changed Callback

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

    }

火很好,一切都很棒。 但是,当我将视图模型连接到自定义控件时,如下所示:

this.DataContext = new LocationInformationViewModel()

该属性已更改回调将不再触发。 我假设它是因为我正在更改控件的数据上下文,因此它将不再找到FarmerID。 但是,无论如何我可以像这样设置一个ViewModel并且在同一个控件上仍然有一个依赖属性?

谢谢你,亚伦

UserControlDataContext设置为自身,或者在您的情况下, 从该控件内部设置视图模型是一个常见的错误。 有许多初学者教程展示了这一点,但这仅仅是因为它是在WPF中将数据导入UI的最快捷,最简单的方法之一。 [当然,也例外。]

因此,不要在内部将DataContext设置为视图模型,而是从UserControl内部BindingUserControl属性,如下所示:

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

...不要'设置DataContext并使用以下RelativeSource Binding

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

这样,无论是否设置了DataContextBinding都会在LocationInformationControl控件中查找FarmerID 几乎可以将其视为设置DataContext ,但仅限于此一个Binding

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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