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