Prismで用意されているDelegateCommandはObservesPropertyメソッドを指定することによってCanExecuteを再評価してくれる。しかもメソッドチェーンで複数指定可能。
プロパティをネストして指定したり重複する場合、どういう挙動をするのかメモ。
実行するコード
public static class TestCode {
public static void Main(string[] args) {
var root = new RootClass();
root.NotifyObject = new NotifyObj() { Name = "test1" };
root.NotifyObject.Name = "test2";
root.NotifyObject = new NotifyObj() { Name = "test3" };
root.NotifyObject.Name = "test4";
Console.ReadKey();
}
}
用意したコード
public class RootClass : BindableBase {
public RootClass() {
Command = new DelegateCommand(() => { })
.ObservesProperty(() => NotifyObject)
.ObservesProperty(() => NotifyObject.Name);
Command.CanExecuteChanged += (s, e) => { Console.WriteLine($"changed! {NotifyObject.Name}"); };
}
NotifyObj notify = new NotifyObj();
public NotifyObj NotifyObject {
get { return notify; }
set {
SetProperty(ref notify, value);
}
}
DelegateCommand Command { get; set; }
}
public class NotifyObj : BindableBase {
public NotifyObj() { }
string name = "default";
public string Name {
get { return name; }
set {
this.SetProperty(ref name, value);
}
}
}
NotifyObjectが変更されると二重でCanExecuteChangedが呼ばれている。
ということで以下のように記述すれば重複して呼び出されない。
public class RootClass : BindableBase {
public RootClass() {
Command = new DelegateCommand(() => { })
.ObservesProperty(() => NotifyObject.Name);
Command.CanExecuteChanged += (s, e) => { Console.WriteLine($"changed! {NotifyObject.Name}"); };
}
//以下略
}