【发布时间】:2015-01-28 20:06:31
【问题描述】:
我正在尝试实现一个 MVVM UserControl,用于编辑有关单个类实例(例如 Person 类的实例)的信息。我创建了一个视图、一个 ViewModel 和一个模型。当我的应用程序启动视图时,视图会自动在其 DataContext 中实例化一个 ViewModel。 ViewModel 使用 Model 类的新实例进行实例化。
现在,当我将不同的 Person 分配给 ViewModel.Source 属性时,视图中的属性不会更新(因为 DataContext 没有更改,而且我没有引发 PropertyChanged 事件。当然,我可以在所有属性上引发属性更改事件当分配一个新的 Person 实例时,ViewModel 类的名称。但这合适吗?有没有更好的方法?我是否必须为每个 Person 实例创建一个新的 ViewModel,然后将其分配给 View.DataContext?
这 3 个类大概是这样的:
<UserControl x:Class="PersonView" xmlns:vm="clr-namespace:MyNamespace">
<UserControl.Resources>
<vm:PersonViewModel x:Key="viewmodel" />
</UserControl.Resources>
<Grid>
<TextBox x:Name="txLastName" Grid.Row="1" Grid.Column="1" Text="{Binding Path=txLastName}" />
</Grid>
</UserControl>
代码:
public class PersonViewModel : INotifyPropertyChanged
{
private Person _source;
public Person Source
{
get
{
if (_source == null) _source = new Person();
return _source;
}
set
{
_source = value;
//should I now raise property changed on each property?
}
}
public String txLastName
{
get { return Source.LastName; }
set
{
Source.LastName = value;
this.RaisePropertyChanged("txLastName");
}
}
}
public class Person
{
public String LastName { get; set; }
}
【问题讨论】: