首页 文章

将模型的另一个实例分配给ViewModel

提问于
浏览
1

我正在尝试实现一个MVVM UserControl,用于编辑有关单个类实例的信息(例如Person类的实例) . 我创建了一个View,一个ViewModel和一个Model . 当我的应用程序启动View时,View会自动在其DataContext中实例化ViewModel . ViewModel使用Model类的新实例进行实例化 .

现在,当我为ViewModel.Source属性分配一个不同的Person时,属性不会在View中更新(因为DataContext没有改变,我没有提出PropertyChanged事件 . 当然我可以在ViewModel的所有属性上引发属性更改事件分配一个新的Person实例时的类 . 但这是否合适?没有更好的方法吗?我是否必须为每个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; }
}

1 回答

  • 1

    如果以这种方式构造绑定,则是,当您更改 Source 时,您将需要针对依赖于它的任何属性引发属性更改通知 . 请注意 RaisePropertyChanged(string.Empty) 通常被解释为'all properties changed'的潜在快捷方式 .

    如果ViewModel中没有属性组合(即所有都是示例中的简单委托),并且模型的属性不会更改(或者,如果它们可以更改,则模型实现 INotifyPropertyChanged )则绑定可能更简单直接到模型(例如 {Binding Path=Source.LastName} ) . 这样,当 Source 更改时,依赖于 Source 的所有绑定都将更新 .

相关问题