Reputation: 691
I am having problems with updating the UI after updating my ObservableCollection property.
My constructor:
public ObservableCollection<Positions> Positions { get; set; }
public BindableBase BindableBase { get; set; }
public MainWindow()
{
InitializeComponent();
Positions = new ObservableCollection<Positions>();
BindableBase = new BindableBase();
Positions.Add(new Positions
{
Position1 = "Red",
Position2 = "Red",
Position3 = "Red",
Position4 = "Gray",
Position5 = "Green",
Position6 = "Green",
Position7 = "Green",
});
this.DataContext = this;
}
This is the if statement that changes the values inside of the ObservableCollection and then I call the RaisePropertyChanged event with the name of my property. Because I did not include all the code, imagine that it goes inside the ifstatement.
if (Positions[0].Position4 == "Gray")
{
Positions[0].Position1 = "Red";
Positions[0].Position2 = "Red";
Positions[0].Position3 = "Gray";
Positions[0].Position4 = "Red";
Positions[0].Position5 = "Green";
Positions[0].Position6 = "Green";
Positions[0].Position7 = "Green";
BindableBase.RaisePropertyChanged("Positions");
}
This is my code to RaisePropertyChanged:
public class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
The problem is that, it does not update the UI if I call the RaisePropertyChanged event. After some debugging I found out that the PropertyChanged has the value NULL, so it won't be updated even tho I made a change. Does anyone how to fix this problem?
Upvotes: 0
Views: 1650
Reputation: 128013
PropertyChanged
is always null because there is no Binding that actually uses the BindableBase
property value as source object (the source object is the MainWindow, by DataContext = this
).
Fortunately you don't need the BindableBase here. Positions is an ObservableCollection, and doesn't need any additional property change notification. If it would need one, Positions had to be a property of BindableBase, otherwise firing the PropertyChanged event is pointless.
Replace
Positions[0].Position1 = "Red";
Positions[0].Position2 = "Red";
Positions[0].Position3 = "Gray";
Positions[0].Position4 = "Red";
Positions[0].Position5 = "Green";
Positions[0].Position6 = "Green";
Positions[0].Position7 = "Green";
by
Positions[0] = new Positions
{
Position1 = "Red",
Position2 = "Red",
Position3 = "Gray",
Position4 = "Red",
Position5 = "Green",
Position6 = "Green",
Position7 = "Green",
};
Besides that, replace the combination of null
check and PropertyChanged.Invoke
by this:
public void RaisePropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
Upvotes: 1