Device Association

I find that I repeat a lot, and this, of course, is not good. So I wondered if I could do anything about it. This is the regular code in my WPF application:

private string _name; public string Name { get { return _name; } set { if (_name != value) { _name = value; OnPropertyChanged("Name"); } } } 

So I was wondering if I could somehow wrap the setter to make it better and more readable. One idea was something like this:

 protected void PropertySetter<T>(T property, T value, string name) { if (EqualityComparer<T>.Default.Equals(property, value)) { property = value; OnPropertyChanged(name); } } 

Using:

 private string _name2; public string Name2 { get { return _name2; } set { PropertySetter<string>(Name2, value, "Name2"); } } 

But I'm not sure if this is really smart or will it work with value types?

I guess I'm not the first to try something like this, so if someone knows a good reliable way to do something like this, please call back. I suppose I could not make the Changed typeafe property without reflection, but any ideas there also help.

+6
source share
2 answers

Yes - this is a perfectly acceptable and normal code.

Here is an example that I found fairly standardized (I see a lot of this type of use in code samples).

 public event PropertyChangedEventHandler PropertyChanged; private void SetProperty<T>(ref T field, T value, string name) { if (!EqualityComparer<T>.Default.Equals(field, value)) { field = value; var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } } 

Wrap this code inside a class that implements INotifyPropertyChanged , and inherit your data objects from this class.

In your example, you are raising an event directly - never do this. You can lose the link to the event from the moment the method is launched until the event is called. Always create a local event cache before calling it.

+2
source

Maybe this will help you

 public class ObservableObject : INotifyPropertyChanged { #region Events public event PropertyChangedEventHandler PropertyChanged; #endregion #region Protected Methods protected virtual void SetAndNotify<T>(ref T field, T value, Expression<Func<T>> property) { if (!object.ReferenceEquals(field, value)) { field = value; this.OnPropertyChanged(property); } } protected virtual void OnPropertyChanged<T>(Expression<Func<T>> changedProperty) { if (PropertyChanged != null) { string name = ((MemberExpression)changedProperty.Body).Member.Name; PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } 

Using:

 private String _myField; public String MyProperty { get { return _myField; } set { SetAndNotify(ref _myField, value, () => MyProperty); } } 

Edit: your class should inherit from this OservableObject class

+2
source

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


All Articles