开发者

ObservableCollection<T> does not update ListBox

开发者 https://www.devze.com 2022-12-12 05:12 出处:网络
I\'ve set the ItemsSource of a ListBox to an ObservableCollection<Employee> collection, and my Employee class implements INotifyPropertyChanged.

I've set the ItemsSource of a ListBox to an ObservableCollection<Employee> collection, and my Employee class implements INotifyPropertyChanged.

On the Employee, I've bound several properties, one of them a Color property, and I've ensured that it invokes the PropertyChanged event when it's changed. I've also checked with the debugger that the PropertyChanged invoke is called.

However, when databound the Background of the ListBoxItem in the bound ListBox does never update, which is extremely fustrating.

Setting the ItemsSource to null, and resetting it after works, but it's not how we're meant to utilize the Observer Pattern.

The XAML used:

<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="开发者_StackOverflowMouseDoubleClick" 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>

More code in response to first reply:

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;


Problem solved.

OnPropertyChanged was called BEFORE the actual value of the property was set, so the UI was updating accordingly to the old value.

Solution: Call OnPropertyChanged after setting the property value.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号