gpt4 book ai didi

c# - ObservableCollection 不更新 ListBox

转载 作者:行者123 更新时间:2023-11-30 17:23:52 25 4
gpt4 key购买 nike

我已经设置了 ItemsSourceListBoxObservableCollection<Employee>收藏,还有我的Employee类(class)工具INotifyPropertyChanged .

关于Employee ,我绑定(bind)了几个属性,其中一个是 Color属性,我确保它调用了 PropertyChanged更改时的事件。我还用调试器检查了 PropertyChanged invoke 被调用。

然而,当数据绑定(bind) BackgroundListBoxItem在界内ListBox 从不更新,这非常令人沮丧。

设置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;

最佳答案

问题已解决。

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

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

关于c# - ObservableCollection<T> 不更新 ListBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1769726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com