![](/img/trans.png)
[英]Adding data to ObservableCollection does not update ListBox entries
[英]ObservableCollection<T> does not update ListBox
我已将ListBox
的ItemsSource
设置为ObservableCollection<Employee>
集合,而我的Employee
类实现了INotifyPropertyChanged
。
在Employee
,我绑定了几个属性,其中一个属性是Color
属性,并且我确保它在更改时调用PropertyChanged
事件。 我还检查了调试器是否调用了PropertyChanged
调用。
但是,当数据绑定时, ListBoxItem
的Background
在绑定的ListBox
中永远不会更新 ,这是非常令人讨厌的。
将ItemsSource
设置为null,并在工作后重置它,但这不是我们如何使用Observer模式。
使用的XAML:
<Style TargetType="{x:Type ListBoxItem}">
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}"
Color="{x:Static SystemColors.HighlightColor}" />
</Style.Resources>
<Setter Property="Foreground" Value="White" />
<Setter Property="Background"
Value="{Binding Path=Color, Converter={StaticResource ColorConverter}}" />
<Setter Property="Content" Value="{Binding Path=Name}" />
<Setter Property="Height" Value="25" />
<Setter Property="Margin" Value="0,1,0,1" />
<EventSetter Event="MouseDoubleClick" Handler="HelperList_MouseDoubleClick" />
</Style>
<ListBox x:Name="helperList" Grid.Column="0" Grid.Row="1"
Margin="5,2,0,5" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
ScrollViewer.VerticalScrollBarVisibility="Visible"
SelectionChanged="HelperList_SelectionChanged">
</ListBox>
响应第一个回复的更多代码:
public class Employee : Person
{
private EmployeeColor color = new EmployeeColor();
public EmployeeColor Color
{
get { return this.color; }
set
{
if(!this.color.Equals(value))
OnPropertyChanged("Color");
this.color = value;
}
}
}
var employees = new ObservableCollection<Employee>();
//... fill out data here
helperList.ItemsSource = employees;
问题解决了。
在设置属性的实际值之前调用OnPropertyChanged,因此UI相应地更新为旧值。
解决方案:设置属性值后调用OnPropertyChanged。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.