0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PrismのDelegateCommand.ObservesPropertyのテスト

Last updated at Posted at 2023-11-05

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);
            }
        }
    }

実行結果は以下
screenshot.12.jpg

NotifyObjectが変更されると二重でCanExecuteChangedが呼ばれている。
ということで以下のように記述すれば重複して呼び出されない。

	public class RootClass : BindableBase {
		public RootClass() {
			Command = new DelegateCommand(() => { })
                .ObservesProperty(() => NotifyObject.Name);
            
			Command.CanExecuteChanged += (s, e) => { Console.WriteLine($"changed! {NotifyObject.Name}"); };
		}
        //以下略
    }

screenshot.12.jpg
というわけで、同名プロパティ変更通知は重複する。
可能な限り対象のインスタンスのメンバーで完結させたい。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?