3

我已经将 a 设置ItemsSourceListBox一个ObservableCollection<Employee>集合,并且我的Employee类实现了INotifyPropertyChanged.

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

但是,当数据绑定时,绑定中的永远Background不会更新,这非常令人沮丧。ListBoxItemListBox

将其设置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;
4

1 回答 1

2

问题解决了。

在设置属性的实际值之前调用 OnPropertyChanged,因此 UI 会相应地更新为旧值。

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

于 2009-11-20T16:07:09.883 回答