厳密な名前のOnPropertyChanged

OnPropertyChangedに怒り狂っています。 識別子名を含む文字列を渡す必要があります...このコードはコンパイラによって検証されないだけでなく、Intellisenceもありません-識別子全体を最初から最後までタップします...そして、あなたが悪くなると、実行時に飲み込まれます。 一般的に、悪いことです。 しかし、MVVMなしのWPFのように、MVVMなしでは、どこにもありません。

最後の問題は、OnPropertyChangedから呼び出された、 ここから引き裂かた松葉杖で少なくとも解決されました。
[Conditional( "DEBUG" )]
[DebuggerStepThrough]
public void VerifyPropertyName( string propertyName)
{
// Verify that the property name matches a real,
// public, instance property on this object.
if (TypeDescriptor.GetProperties( this )[propertyName] == null )
{
string msg = "Invalid property name: " + propertyName;

if ( this .ThrowOnInvalidPropertyName)
throw new Exception(msg);
else
Debug.Fail(msg);
}
}


そして今日、それを取り除く美しい方法を偶然見つけました。

解決策は美しく、同時に単純であることがわかりました。次のようにExpressionを使用します。
this .OnPropertyChanged(() => this .ShowOverrideButton);

これを行うには、基本クラスでオーバーロードを作成するだけです。
protected void OnPropertyChanged<T>(Expression<Func<T>> property)
{
PropertyChangedEventHandler handler = this .PropertyChanged;
if (handler != null )
{
var expression = property.Body as MemberExpression;
if (expression == null )
{
throw new NotSupportedException( "Invalid expression passed. Only property member should be selected." );
}

handler( this , new PropertyChangedEventArgs(expression.Member.Name));
}
}


* This source code was highlighted with Source Code Highlighter .

できた OnPropertyChangeの行を忘れることがあります。 バインディングのXAMLにはまだ悪い行があります-しかし、私はそれらをどのように取り除くか全く分かりません。


Source: https://habr.com/ru/post/J103991/


All Articles