开发者

Is passing DependencyProperty which gets updated to a ViewModel a good practice?

开发者 https://www.devze.com 2023-01-10 13:40 出处:网络
I have a custom user control, and it has a dependency property. That custom user control is kind of complicated so I decided to make a view model for it, but I haven\'t implemented it yet. I\'m thinki

I have a custom user control, and it has a dependency property. That custom user control is kind of complicated so I decided to make a view model for it, but I haven't implemented it yet. I'm thinking of making the view model having some properties which are bound to the custom user control.

Here is my code sample,

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 p开发者_开发技巧ropertyChangedCallback(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; }

So, do you think it's a good practice? I mean updating a view model when a dependency property gets updated, and hopefully someone teaches me how to update the view model inside the PropertyChangedCallback :) BTW I'm using the MVVM Light toolkit.


According to this question, http://forums.silverlight.net/forums/p/133665/298671.aspx, I can't use a view model as the DataContext of a user control to bind some UI in a usual way.

0

精彩评论

暂无评论...
验证码 换一张
取 消