设置
让我们假设以下。 我们有一个下面的 理论 模型类WPF应用程序:
public MyViewModel
{
public MyViewModel()
{
// Condition under which this command may be executed is:
// this.ActiveDocument.Highlighting.Type == Highlighting.Xml &&
// !this.ActiveDocument.IsReadOnly &&
// (this.License.Kind == LicenseKind.Full || this.License.TrialDay < 30)
MyCommand = new Command(obj => DoSomething());
}
public ICommand MyCommand { get; }
// (all other required properties)
}
此外:
- 目前的类实现正常
INotifyPropertyChanged
- 所有类别中的成员访问链,实现了正确
INotifyPropertyChanged
(eg. 文档模型可以从ActiveDocument
酒店) ActiveDocument
可null
.ActiveDocument.Highlighting
也可以空。
的问题
我会喜欢的命令时才会启用的条件的意见得到满足。
选项而RX
我写了 我自己的图书馆 处理这种情况。 该方案将:
public MyViewModel
{
private readonly Condition commandAvailableCondition;
public MyViewModel()
{
commandAvailableCondition = new LambdaCondition(this,
vm => m.ActiveDocument.Highlighting.Type == Highlighting.Xml &&
!vm.ActiveDocument.IsReadOnly &&
(vm.License.Kind == LicenseKind.Full || vm.License.TrialDay < 30),
false);
MyCommand = new AppCommand(obj => DoSomething(), commandAvailableCondition);
}
public ICommand MyCommand { get; }
// (all other required properties)
}
或者-如果你想要代码是一点点更具可读性,使得局部的条件可能重复使用这样的:
public MyViewModel
{
private readonly Condition commandAvailableCondition;
public MyViewModel()
{
var highlightingIsXml = new LambdaCondition(this,
vm => vm.ActiveDocument.Highlighting.Type == Highlighting.Xml,
false);
var documentIsReadonly = new LambdaCondition(this,
vm => vm.ActiveDocument.IsReadOnly,
false);
var appIsLicensed = new LambdaCondition(this,
vm => vm.License.Kind == LicenseKind.Full || this.License.TrialDay < 30,
false);
commandAvailableCondition = highlightingIsXml & !documentIsReadonly & appIsLicensed;
MyCommand = new AppCommand(obj => DoSomething(), commandAvailableCondition);
}
public ICommand MyCommand { get; }
// (all other required properties)
}
什么我的图书馆(或者,更确切地说, LambdaCondition
class)是:
- 它跟踪所有实例执行
INotifyPropertyChanged
以及处理变化(例如。 时ActiveDocument
变化或者ActiveDocument.Highlighting
变化或者ActiveDocument.Highlighting.Type
变化等。) - 它跟踪的可能
null
s在的方式在这种情况下,它将返回的默认值(在这种情况下,false
) - 它会自动报告的修改(但只有改变)性的命令,以便UI可以刷新,需要的时候。
这个问题
如何能实现上述情况使用 System.Reactive
在C#? 这是能够做到这一点很容易,同时保持所有有关要求 INotifyPropertyChanged
,null的方式和默认的价值? 你可以做任何理智的假设需要的时候。