gpt4 book ai didi

c# - WPF、ObservableCollection/BindingList 绑定(bind)到 ListView

转载 作者:行者123 更新时间:2023-11-30 19:32:12 24 4
gpt4 key购买 nike

我在将 ObservableCollection 绑定(bind)到 LisView 时遇到问题。问题是绑定(bind)仅在我从 ObservableCollection 添加/删除项目时才能正常工作。但是当我更改 ObservableCollection 中一项的属性时,ListView 仍然显示旧值。我知道这是一个常见问题并寻找解决方案,每个人都说我应该使用 BindingList 而不是 ObservableCollectione,因为 ObservableCollection 不传播 PropertyChanged 事件而 BindingList 传播。所以我改为绑定(bind)列表,但问题仍然存在。

类:

public class Network
{
public class Layer : INotifyPropertyChanged
{
public enum ActivFunction { LINEAR, EXPONENTIAL, ARCUSTANGENT }

private string name;

public string Name
{
get
{
return name;
}
set
{
name = value;
RaisePropertyChanged("Name");
}
}

public ActivFunction Activation { get; set; }
public int Neurons { get; set; }

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void RaisePropertyChanged(String propertyName)
{
if ((PropertyChanged != null))
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

}

public BindingList<Layer> Layers { get; set; }

public Network()
{
Layers = new BindingList<Layer>();
}

public void AddLayer(Layer layer)
{
if (Layers.Count > 0)
{
int last = Layers.Count;
Layers.Last().Name = "Layer " + last + " (hidden)";
}
Layers.Add(layer);
}

public void RemoveLayer(int index)
{
if( index >= 0 && index < Layers.Count )
Layers.RemoveAt(index);
}
}

绑定(bind):

<ListView Grid.Row="0" x:Name="NetworkListview" ItemsSource="{Binding network.Layers}"
IsSynchronizedWithCurrentItem="True">
<ListView.View>
<GridView>
<GridViewColumn Width="100" Header="layer name"
DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Width="60" Header="neurons"
CellTemplate="{StaticResource NeuronsTemplate}"/>
<GridViewColumn Width="110" Header="activation"
CellTemplate="{StaticResource ActivationTemplate}"/>
</GridView>
</ListView.View>
</ListView>

最佳答案

您集合中的项目应该是实现 INotifyPropertyChanged 接口(interface)的类型。这样您的 ListView 将被通知您的单个项目对象中的属性值已更改。 ObservableCollection 仅在集合更改(添加、删除项目等)时引发 CollectionChanged 事件

引用自关于 ObservableCollection 的 MSDN 库文章

To fully support transferring data values from binding source objects to binding targets, each object in your collection that supports bindable properties must implement an appropriate property changed notification mechanism such as the INotifyPropertyChanged interface.

是的,如果你想将处理程序附加到你的子元素属性 chnaged 事件,请查看这个问题的答案如何做,虽然问题有点不同,但我认为答案会满足你的目的 - Observable Collection Property Changed on Item in the Collection

关于c# - WPF、ObservableCollection/BindingList 绑定(bind)到 ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5847329/

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