ObservableCollection<T>无法更新ListBox。

3

我已经将一个ListBoxItemsSource设置为一个ObservableCollection<Employee>集合,我的Employee类实现了INotifyPropertyChanged

Employee中,我绑定了几个属性,其中一个是Color属性,并确保它在更改时调用了PropertyChanged事件。我还使用调试器检查了PropertyChanged调用是否被调用。

然而,在数据绑定到的ListBox中,绑定的ListBoxItemBackground永远不会更新,这非常令人沮丧。

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;

1
没问题,你能提供更多的代码吗?"Employer class"是什么意思?你如何设置ItemSource? - Arsen Mkrtchyan
完成了,请检查更新后的代码。虽然很明显,但我只是将ItemSource属性设置为ObserverableCollection! - Claus Jørgensen
2
你的ColorConverter里面有什么?它是否按照Background属性所期望的将颜色转换为画刷?我怀疑问题就出在这里。 - Mart
它也不能工作在任何其他属性上。是的,它转换得很好。正如我之前所说,将ItemSource设置为null,然后再设置为相同的ObserveableCollection<T>就可以使其工作。但这并不是正确的做法。 - Claus Jørgensen
1个回答

2

问题已解决。

在设置属性的实际值之前,已经调用了OnPropertyChanged,因此UI根据旧值进行更新。

解决方案:在设置属性值之后调用OnPropertyChanged。


听起来很合理。 :) 只有在设置值后,属性才会更改。 还存在一个INotifyPropertyChanging接口... - Frederik Gheysels

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接