2
我有一个自定义的用户控件,它有一个依赖属性。该自定义用户控件有点复杂,所以我决定为它创建一个视图模型,但是我还没有实现它。我正在考虑让视图模型具有一些绑定到自定义用户控件的属性。传递给ViewModel更新的DependencyProperty是一个好习惯吗?
这里是我的代码示例,
UserControl.xaml
<StackPanel>
<TextBlock Text={Binding Age} />
<TextBlock Text={Binding Name} />
</StackPanel>
UserControl.cs
public Person Person
{
get { return (Person)GetValue(PersonProperty); }
set { SetValue(PersonProperty, value); }
}
public static readonly DependencyProperty PersonProperty = DependencyProperty.Register("Person", typeof(Person), typeof(SampleUserControl), new PropertyMetadata(null, propertyChangedCallback));
private static void propertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// I want to update the view model here
// Something like the following
(this.DataContext as MyViewModel).Person = Person;
}
MyViewModel
public Person Person
{
get { return _person; }
set
{
_pserson = person;
RaisePorpertyChanged("Age");
RaisePorpertyChanged("Name");
}
}
public int Age{ get; set; }
public string Name{ get; set; }
那么,你认为这是一个很好的实践?我的意思是更新视图模型,当一个依赖项属性得到更新,并希望有人教我如何更新PropertyChangedCallback内的视图模型:)顺便说一句我正在使用MVVM Light工具包。
欢迎来到SO,请花几分钟的时间阅读常见问题和Markdown文档(在编辑问题时右边空白处提供有用的synposis)。 – AnthonyWJones 2010-08-05 12:14:37