FPGA
FPGA

Reputation: 3865

Setting the value of property in multiple objects on property changed of some object

in my model i have the following property

private string somestring;
public string SomeString
        {
            get
            {
                return somestring;
            }
            set
            {
                SetField(ref somestring, value, "SomeString");
            }
        }

and in my view model i have an ObservableCollection which represents selected objects

private ObservableCollection<Models.model> selectedObjects
public ObservableCollection<Models.model> SelectedObjects
        {
            get
            {
                return selectedObjects;
            }
            set
            {
                SetField(ref selectedObjects, value, "SelectedObjects");
            }
        }

suppose i want to set the same value of property for every object in the collection whenever that property value changes in the currentObject so i came up with this in my viewmodel

 private void SetMultiplePropertyValues<T>(string propName, object value)
        {
            if(!SelectedObjects.Contains(currentObject)) return;
            var p = typeof(T).GetProperty(propName);
            foreach (var obj in SelectedObjects)
            {
                p.SetValue(obj, value, null);
            }

        }

is there a more convenient way than calling that function when ever a property changes

Upvotes: 1

Views: 633

Answers (1)

dev hedgehog
dev hedgehog

Reputation: 8791

Here is an example:

interface IObjectWithOnPropertyChangedMethod
{
  void OnPropertyChanged(string propertyName);
}

public class MyPoco : INotifyPropertyChanged, IObjectWithOnPropertyChangedMethod
{
  //// Implementation of IObjectWithOnPropertyChangedMethod interface
  public void OnPropertyChanged(string propertyName)
  {
    if(PropertyChanged != null)
    {
       PropertyChanged(.....);
    }
  }

 //// Implementation of INotifyPropertyChanged interface
 public event PropertyChanged;
}

Something like that and now when you want to fire OnPropertyChanged though your list of objects just do something like this:

foreach (var obj in list)
{
  if(obj is IObjectWithOnPropertyChangedMethod)
  {
    ((IObjectWithOnPropertyChangedMethod)obj).OnPropertyChanged("MyProperty");
  }
}

I hope this helps.

Upvotes: 2

Related Questions