简体   繁体   English

WPF用户控件依赖项属性绑定

[英]Wpf usercontrol dependency Property Binding

In my mainwindow I have got an UserControl, which ViewModel has got the Dependency Property "Message", I'm trying to bind the Dependency Property to an Property of the ViewModel of the Main Window, but actually it isn't Working, is there any soulution or is it genarally impossible? 在我的主窗口中,我有一个UserControl,它的ViewModel有Dependency属性“ Message”,我试图将Dependency属性绑定到主窗口的ViewModel的属性,但实际上它不起作用,是否存在有任何解决方案,或者通常是不可能的吗?

Content of the Main Window: 主窗口的内容:

    <local:MessageLayer>
        <local:MessageLayer.DataContext>
            <local:MessageBoxViewModel Message="{Binding RelativeSource={RelativeSource AncestorType=Window, Mode=FindAncestor}, Path=DataContext.Message}"/>
        </local:MessageLayer.DataContext>
    </local:MessageLayer>

View models should not have DependencyProperty s in them and should certainly not extend the DependencyObject class, because these are UI related classes. 查看模型应该DependencyProperty在其中S和当然不应延长DependencyObject类,因为这些都是UI相关的类。 I'm sure that you, along with many others have been confused by Microsoft's terribly worded error below: 我确信您和其他许多人都被Microsoft措辞严重的错误所迷惑:

A 'Binding' can only be set on a DependencyProperty of a DependencyObject . 只能在DependencyPropertyDependencyObject上设置“ Binding”。

This is really only referring to the UI element side of Binding s and not the data element side. 这实际上仅指Binding的UI元素,而不是数据元素。 For data binding data objects, we implement the INotifyPropertyChanged interface instead, which provides similar property change notification functionality to DependencyProperty s. 对于数据绑定数据对象,我们改为实现INotifyPropertyChanged接口 ,该接口提供与DependencyProperty相似的属性更改通知功能。

So, had you set the Window.DataContext to an instance of a view model that implemented INotifyPropertyChanged , with a property declared in it named Message , then your code would have worked just fine: 因此,如果您将Window.DataContext设置为实现INotifyPropertyChanged的视图模型实例,并在其中声明了一个名为Message的属性,那么您的代码就可以正常工作:

<local:MessageLayer>
    <local:MessageLayer.DataContext>
        <local:MessageBoxViewModel Message="{Binding RelativeSource={RelativeSource 
            AncestorType=Window, Mode=FindAncestor}, Path=DataContext.Message}"/>
    </local:MessageLayer.DataContext>
</local:MessageLayer>

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

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