Edw*_*uay 6 wpf dependency-properties mvvm inotifypropertychanged
我正在使用DependencyProperties 构建一个简单的UserControl示例,以便可以在XAML(下面的代码)中更改控件的属性.
但是当然在我的应用程序中我不希望这个控件具有紧密耦合的代码隐藏,而是用户控件将是一个名为"DataTypeWholeNumberView"的视图,它将拥有自己的ViewModel,称为"DataTypeWholeNumberViewModel".
所以我将把下面的DependencyProperty逻辑实现到ViewModel中,但是在ViewModel中我通常会继承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>
Run Code Online (Sandbox Code Playgroud)
代码背后:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
INotifyPropertyChanged是自2.0以来存在于.Net中的接口.它基本上允许对象在属性发生变化时进行通知.当引发此事件时,感兴趣的一方可以执行某些操作.它的问题是它只发布属性的名称.所以你最终使用反射或一些iffy if语句来弄清楚在处理程序中要做什么.
DependencyProperties是一个更复杂的构造,它支持默认值,以更高内存效率和高性能的方式更改通知.
唯一的关系是WPF绑定模型支持使用INotifyPropertyChanged实现绑定到DependencyProperties或标准Clr属性.您的ViewModel也可以是DependecyObject,第三个选项是绑定到ViewModel的DependencyProperties!
Kent Boogaart撰写了一篇非常有趣的文章,介绍了如何将ViewModel作为POCO与DependencyObject.
我真的不认为 DependencyProperties 和 INotifyPropertyChanged 之间存在关系。这里唯一的魔力是 Binding 类/utils 足够智能,可以识别 DependencyProperty 并直接绑定到它,或者订阅绑定目标的 notification-property-changed 事件并等待该事件触发。
| 归档时间: |
|
| 查看次数: |
3911 次 |
| 最近记录: |