📜 ⬆️ ⬇️

OnPropertyChanged with strong names

OnPropertyChanged infuriates me wildly. It requires the transfer of the string with the name of the identifier to it ... Not only is such a code not verified by the compiler, so there is no Intellisence - the type is all from beginning to end ... And if you type it, it will swallow it at runtime. In general, not a good thing. But in MVVM without it anywhere, as in WPF without MVVM.

The last problem was somehow solved by such a crutch, stripped from here , which was called from 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);
}
}


And today I accidentally found a beautiful way to get rid of it.

The solution turned out to be beautiful and at the same time simple to the banality: use Expression, like this:
this .OnPropertyChanged(() => this .ShowOverrideButton);

To do this, you just need to create an overload in the base class:
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 .

Is done. You can forget about the strings in OnPropertyChange. There are still bad lines in XAML in Binding - but I have absolutely no idea how to get rid of them.

')

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


All Articles