我已经将一个ListBox
的ItemsSource
设置为一个ObservableCollection<Employee>
集合,我的Employee
类实现了INotifyPropertyChanged
。
在Employee
中,我绑定了几个属性,其中一个是Color
属性,并确保它在更改时调用了PropertyChanged
事件。我还使用调试器检查了PropertyChanged
调用是否被调用。
然而,在数据绑定到的ListBox
中,绑定的ListBoxItem
的Background
永远不会更新,这非常令人沮丧。
将ItemsSource
设置为null,然后重新设置它可以解决问题,但这不是我们应该使用观察者模式的方式。
所使用的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;