StaticPropertyの変更通知

かねがねStaticなプロパティの変更通知ができないか困っておりました。

ありました。
StaticPropertyChanged

.Net 4.5からだそうで、英語読めないので見つけられませんでした。


よくわからないのですが、StaticPropertyChangedイベントを呼び出せばいいみたいです。
staticなのでinterfaceとか使えないので勝手にイベントを追加するだけのようです。

public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;

こういうことだー

using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace ねーむすぺーす.Models {
	public class TestClass {
		static public string CurrentValue {
			get { return _CurrentValue; }
			set {
				if( _CurrentValue != value ) {
					_CurrentValue = value;
					NotifyStaticPropertyChanged();
				}
			}
		}
		static private string _CurrentValue = "てすと";

		public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;
		private static void NotifyStaticPropertyChanged( [CallerMemberName] string propertyName = "" ) {
			if( StaticPropertyChanged != null )
				StaticPropertyChanged( null, new PropertyChangedEventArgs( propertyName ) );
		}
	}
}

こう使います。

<!-- m に対してネームスペースを追加して -->
<Window xmlns:m="clr-namespace:ねーむすぺーす.Models">

<!-- Path は省略できません Staticな部分の()カッコ重要 -->
<TextBlock Text="{Binding Path=(m:TestClass.CurrentValue)}" />

Staticのクラス内を参照する場合はこんな感じになります。
※プロパティ名とか適当です

<TextBlock Text="{Binding Path=(m:TestClass.CurrentModel).Value}"/>

追記:
()カッコで簡潔に記述できるのですが、Xamlデザイナーがエラー出まくるのでXamlの方でリソースを作成したほうが良さそうです。

<Window.Resources>
	<m:TestClassx:Key="TestClass" />
</Window.Resources>

<TextBlock Text="{Binding CurrentValue, Source={StaticResource TestClass}}" />

<!-- クラス(TestClass)がstatic(public static class TestClass {...})ならリソースの作成は必要ないです。-->
<TextBlock Text="{Binding CurrentValue, Source={x:Static m:TestClass}}" />


詳しくは参考URLへどうぞ(丸投げ)

参考:
WPF 4.5 での バインディング強化
WPF 4.5: Binding and change notification for static properties - Pete Brown's 10rem.net
WPF 4.5 – Part 9 : binding to static properties UPDATED | Jonathan ANTOINE's thoughts on Windows development