gpt4 book ai didi

c# - 公开原始模型而不是单个属性时的 INotifyPropertyChanged

转载 作者:行者123 更新时间:2023-12-03 10:13:32 25 4
gpt4 key购买 nike

这是我目前实现INotifyPropertyChanged的方式-

public class ViewModel : INotifyPropertyChanged
{
public Person Person1 { get; set; }
public Person Person2 { get; set; }

public string Person1Name
{
get { return Person1.Name; }
set
{
Person1.Name = value;
RaisePropertyChangedEvent("Person1Name");
}
}

public string Person2Name
{
get { return Person2.Name; }
set
{
Person2.Name=value;
RaisePropertyChangedEvent("Person2Name");
}
}
}

//This is the Model
public class Person
{
private string _name;
public string Name { get; set; }
}

以及我用于此类实现的 XAML -

<Label Text="{Binding Path=Person1Name}"/>
<Label Text="{Binding Path=Person2Name}"/>

我想要做的是每当模型中的任何属性发生更改时 IRaisePropertyChangedEvent,但我不想像我在那里那样显式公开该属性。我只是想公开整个模型,并且每当模型中的属性发生更改时,它都应该引发通知事件。但我不希望模型实现 INotifyPropertyChanged,我希望 ViewModel 实现它。所以基本上我正在寻找的是这样的 -

public class ViewModel : INotifyPropertyChanged
{
public Person Person1
{
get { return _person1; }
set
{
_person1 = value;
RaisePropertyChangedEvent("Person1");
//So, whenever a property within my Person1 changes, raise event for that property.
}
}
public Person Person2
{
get { return _person2; }
set
{
_person2 = value;
RaisePropertyChangedEvent("Person2");
}
}
}

XAML:

<Label Text="{Binding Path=Person1.Name}"/>
<Label Text="{Binding Path=Person2.Name}"/>

我该怎么做?如果觉得问题不清楚,请评论,我会尽力做得更好。

最佳答案

问题是,除非 Person 实现 INotifyPropertyChanged,否则您无法跟踪 person 实例中的属性何时发生更改。

像这样的绑定(bind):

 <Label Text="{Binding Path=Person1.Name}"/>

不会更改 Person1 实例,而是更改同一实例中的属性。除非该类实现 INPC,否则您永远不会“看到”属性已更改,也永远不会引发事件。

关于c# - 公开原始模型而不是单个属性时的 INotifyPropertyChanged,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16862669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com