仅查看Model OnPropertyChanged的更新,而不查看ViewModel OnPropertyChanged的更新

时间:2018-08-19 17:04:44

标签: c# wpf data-binding

我有一个ViewModel托管Model类的属性,其中ViewModel和Model都实现INotifyPropertyChanged

但是,仅当更改模型中的属性时,视图才会更新。如果在ViewModel中更改了属性,则视图不会更新。

模型库:

public class BaseModel : INotifyPropertyChanged
{
    private int id;

    public int Id
    {
        get { return id; }
        set { id = value; OnPropertyChanged(new PropertyChangedEventArgs("Id")); }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(PropertyChangedEventArgs propertyChangedEventArgs)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyChangedEventArgs.PropertyName));
    }
}

模型(视图中显示了对Positionen-Collection的添加和删除):

public class ChildModel : BaseModel 
{

    private ObservableCollection<SubModel> positionen;

    public ObservableCollection<SubModel> Positionen
    {
        get { return positionen; }
        set { positionen = value; OnPropertyChanged(new PropertyChangedEventArgs("Positionen")); }
    }
}

ViewModel库:

public abstract class BaseViewModel<T> where T : BaseModel , INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;


    protected void OnPropertyChanged(PropertyChangedEventArgs propertyChangedEventArgs)
    {
        PropertyChanged?.Invoke(this, propertyChangedEventArgs);
    }


    public abstract ObservableCollection<T> DatensatzListe { get; set; }

    public abstract T AktuellerDatensatz { get; set; }

}

ViewModel子项(对此处属性的更新未在视图中显示)

public class ChildViewModel : BaseViewModel<ChildModel >
{
    public override ObservableCollection<ChildModel > DatensatzListe
    {
        get { return DatensatzListe; }
        set { DatensatzListe = value; }
    }

    private ChildModel aktuellerDatensatz;

    public override ChildModel AktuellerDatensatz
    {
        get { return aktuellerDatensatz; }
        set { aktuellerDatensatz = value; OnPropertyChanged(new PropertyChangedEventArgs("AktuellerDatensatz")); }
    }

    private string tesxt;

    public string Tesxt
    {
        get { return tesxt; }
        set { tesxt = value; OnPropertyChanged(new PropertyChangedEventArgs("Tesxt")); }
    }
}

如果我在后面的代码中更新了Tesxt属性,则更新不会显示在视图中。我更新了AktuellerDatensatz.Id,所做的更改就很好了。

我该如何解决。如果需要更多代码,请告诉我。

1 个答案:

答案 0 :(得分:2)

根据以下定义

public abstract class BaseViewModel<T> where T : BaseModel , INotifyPropertyChanged

BaseViewModel不是从INotifyPropertyChanged派生的,因此视图不知道其更改。

在上面的代码中,INotifyPropertyChanged是对T的约束,其中T必须来自BaseModelINotifyPropertyChanged

更新到

public abstract class BaseViewModel<T>: INotifyPropertyChanged 
    where T : BaseModel

因为BaseModel已从INotifyPropertyChanged派生