Van*_*nel 3 c# inheritance mvvm object-composition
我正在使用MVVM模式.NET Framework 4.6.1开发WPF.和C#.
我的问题不是关于WPF,而是关于使用组合而不是继承这两个类:
public class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChangedEvent(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
Run Code Online (Sandbox Code Playgroud)
和:
public class MainViewModel : ObservableObject
{
private string statusPrinter;
public string StatusPrinter
{
get { return statusPrinter; }
set
{
statusPrinter = value;
RaisePropertyChangedEvent("StatusPrinter");
}
}
}
Run Code Online (Sandbox Code Playgroud)
MainViewModel继承自我ObservableObject,我不想使用继承.
我可以做这个:
public class MainViewModel
{
private string statusPrinter;
private ObservableObject observable;
public string StatusPrinter
{
get { return statusPrinter; }
set
{
statusPrinter = value;
observable.RaisePropertyChangedEvent("StatusPrinter");
}
}
public MainViewModel()
{
observable = new ObservableObject();
}
}
Run Code Online (Sandbox Code Playgroud)
但它似乎是一个问题public event PropertyChangedEventHandler PropertyChanged;的ObservableObject时候我用的组合物.问题出在XAML链接时.
我可以在这里使用组合还是必须使用继承?
你不能在这里使用作文,至少不是你提出的方式.当某些东西想要订阅MainViewModel对象的属性更改通知时- 它将首先检查是否有MainViewModel实现INotifyPropertyChanged.它不适用于您的情况 - 因此它无法通知任何人有关财产变更的信息.
如果你不喜欢继承ObservableObject- 不要.刚刚实施INotifyPropertyChanged的MainViewModel,并没有什么不妥的地方.
| 归档时间: |
|
| 查看次数: |
247 次 |
| 最近记录: |