首页 文章

INotifyPropertyChanged和DependencyProperty之间的关系是什么?

提问于
浏览
6

我正在使用DependencyProperties构建 simple UserControl example ,以便可以在XAML(下面的代码)中更改控件的属性 .

但是当然在我的应用程序中我不希望这个控件具有紧密耦合的代码隐藏,而是用户控件将是一个名为“DataTypeWholeNumberView”的视图,它将拥有自己的ViewModel,称为“DataTypeWholeNumberViewModel” .

所以我将把下面的DependencyProperty逻辑实现到ViewModel中,但是在ViewModel中我通常会继承INotifyPropertyChanged,它似乎给了我相同的功能 .

So what is the relationship between:

  • 将UserControl XAML的DataContext绑定到其具有DependencyProperties的 code behind

  • 将UserControl XAML(View)的DataContext绑定到 ViewModel (继承自INotifyPropertyChanged)并具有实现INotifyPropertyChanged功能的属性?

XAML:

<UserControl x:Class="TestDependencyProperty827.SmartForm.DataTypeWholeNumber"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel>
        <StackPanel HorizontalAlignment="Left" VerticalAlignment="Top" Orientation="Horizontal">
            <TextBlock Text="{Binding Label}"/>
        </StackPanel>
    </StackPanel>
</UserControl>

Code Behind:

using System.Windows;
using System.Windows.Controls;

namespace TestDependencyProperty827.SmartForm
{
    public partial class DataTypeWholeNumber : UserControl
    {
        public DataTypeWholeNumber()
        {
            InitializeComponent();
            DataContext = this;
        }

        public string Label
        {
            get
            {
                return (string)GetValue(LabelProperty);
            }
            set
            {
                SetValue(LabelProperty, value);
            }
        }

        public static readonly DependencyProperty LabelProperty =
            DependencyProperty.Register("Label", typeof(string), typeof(DataTypeWholeNumber),
            new FrameworkPropertyMetadata());
    }
}

3 回答

  • 0

    INotifyPropertyChanged是自2.0以来存在于.Net中的接口 . 它基本上允许对象在属性发生变化时进行通知 . 当引发此事件时,感兴趣的一方可以执行某些操作 . 它的问题是它只发布属性的名称 . 所以你最终使用反射或一些iffy if语句来弄清楚在处理程序中要做什么 .

    DependencyProperties是一个更复杂的构造,它支持默认值,以更高内存效率和高性能的方式更改通知 .

    唯一的关系是WPF绑定模型支持使用INotifyPropertyChanged实现绑定到DependencyProperties或标准Clr属性 . 您的ViewModel也可以是DependecyObject,第三个选项是绑定到ViewModel的DependencyProperties!

    Kent Boogaart写了一个very interesting article关于让ViewModel成为POCO和DependencyObject .

  • 9

    我不认为DependencyProperties和INotifyPropertyChanged之间存在关系 . 这里唯一的魔力是Binding类/ utils足够智能识别DependencyProperty并直接绑定到它,或者订阅binding-target的notify-property-changed事件并等待它触发 .

  • 2

    使用WPF,您可以绑定到DependencyProperties或实现INotifyPropertyChanged的Properties . 这是一个选择问题 .

    所以你的问题要么是在代码后面还是在视图模型中 . 既然您已经提到过您不希望紧密耦合的代码,那么最好使用遵循MVVM模式的视图模型 .

    您甚至可以在视图模型中使用DependencyProperties,就像在后面的代码中完成一样 .

相关问题