【发布时间】:2010-10-27 14:16:51
【问题描述】:
我正在使用 DependencyProperties 构建一个简单的 UserControl 示例,以便可以在 XAML 中更改控件的属性(代码如下)。
当然,在我的应用程序中,我不希望该控件具有紧密耦合的代码隐藏,而是用户控件将是一个名为“DataTypeWholeNumberView”的视图,并且它将拥有自己的名为“DataTypeWholeNumberViewModel”的 ViewModel。
所以我将在 ViewModel 中实现下面的 DependencyProperty 逻辑,但在 ViewModels 中我通常继承 INotifyPropertyChanged,这似乎给了我相同的功能。
那么两者是什么关系:
- 将 UserControl XAML 的 DataContext 绑定到其 背后的代码,该代码具有 DependencyProperties
- 将 UserControl XAML(视图)的 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>
代码隐藏:
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());
}
}
【问题讨论】:
标签: wpf mvvm dependency-properties inotifypropertychanged