繁体   English   中英

的ObservableCollection <T> 不更新ListBox

[英]ObservableCollection<T> does not update ListBox

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

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

但是,当数据绑定时, ListBoxItemBackground在绑定的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM