更新ObservableCollection属性后,更新UI时遇到问题。
我的构造函数:
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;
}
这是if语句,它更改ObservableCollection内部的值,然后用我的属性名称调用RaisePropertyChanged事件。因为我没有包含所有代码,所以可以想象它包含在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");
}
这是我的RaisePropertyChanged代码:
public class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
问题在于,如果我调用RaisePropertyChanged事件,它不会更新UI。经过一些调试后,我发现PropertyChanged的值为NULL,因此即使进行更改也不会更新。有人可以解决这个问题吗?
答案 0 :(得分:1)
PropertyChanged
始终为null,因为没有绑定实际使用BindableBase
属性值作为源对象(源对象为MainWindow,DataContext = this
)。
幸运的是,您在这里不需要BindableBase。 Positions是一个ObservableCollection,不需要任何其他属性更改通知。如果需要,Positions必须是BindableBase的属性,否则触发PropertyChanged事件是没有意义的。
替换
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";
作者
Positions[0] = new Positions
{
Position1 = "Red",
Position2 = "Red",
Position3 = "Gray",
Position4 = "Red",
Position5 = "Green",
Position6 = "Green",
Position7 = "Green",
};
除此之外,将null
支票和PropertyChanged.Invoke
的组合替换为:
public void RaisePropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}