Size: 1125
Comment:
|
← Revision 4 as of 2023-09-14 23:04:09 ⇥
Size: 1316
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 7: | Line 7: |
private ObservableCollection<string> _Area = new ObservableCollection<string>(); public ObservableCollection<string> Area |
private BindingList<string> _Area = new BindingList<string>(); public BindingList<string> Area |
Line 11: | Line 11: |
set => SetField(ref _Area, value); | set => SetField<BindingList<string>>(ref _Area, value); |
Line 25: | Line 25: |
I used to use something like this: | Suppose that the value you are setting with SetField is a property of a Model object. You may get an error that says, "A non ref-returning property or indexer may not be used as an out or ref value." There is an easy fix for this. |
Line 27: | Line 27: |
{{{#!highlight csharp public int test { get { return _test; } set { _test = value; OnPropertyChanged(); } |
{{{#!hightlight csharp private BindingList<string> _Area = new BindingList<string>(); public BindingList<string> Area { get => _Area; set => _Area = SetField<BindingList<string>>(value); |
Line 43: | Line 37: |
protected void OnPropertyChanged([CallerMemberName] string propertyName = null) | public event PropertyChangedEventHandler PropertyChanged; protected void SetField<T>(T value, [CallerMemberName] string propertyName = null) |
Line 45: | Line 41: |
if (PropertyChange != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } |
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); return value; |
Line 51: | Line 45: |
And before that we just passed in the name. It was kind of a pain. |
Implementing INotifyPropertyChanged
It's changed a lot over the years. Here is the latest iteration that I use.
Toggle line numbers
1 private BindingList<string> _Area = new BindingList<string>();
2 public BindingList<string> Area
3 {
4 get => _Area;
5 set => SetField<BindingList<string>>(ref _Area, value);
6 }
7
8 //...
9
10 public event PropertyChangedEventHandler PropertyChanged;
11
12 protected void SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
13 {
14 field = value;
15 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
16 }
Suppose that the value you are setting with SetField is a property of a Model object. You may get an error that says, "A non ref-returning property or indexer may not be used as an out or ref value." There is an easy fix for this.
private BindingList<string> _Area = new BindingList<string>(); public BindingList<string> Area { get => _Area; set => _Area = SetField<BindingList<string>>(value); } //... public event PropertyChangedEventHandler PropertyChanged; protected void SetField<T>(T value, [CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); return value; }