当某个 AvaloniaList 元素的字段发生变化时,如何使 ListBox 更新?
最近开始学习C#,使用AvaloniaUI、ReactiveUI和MVVM模式制作了一个项目。
问题的本质是:有一个AvaloniaList(可观察集合),通过绑定的方式将一个ListBox绑定到它上面。
MainWindow.axaml:
<ListBox Items="{Binding Devices}"
SelectedItem="{Binding SelectedDevice}"
SelectionMode="Single, Toggle">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="5">
<TextBlock FontSize="18" Text="{Binding name}" />
<TextBlock Text="{Binding state}" />
<TextBlock Text="{Binding ip}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
视图模型:
private AvaloniaList<Device>? devices;
public AvaloniaList<Device> Devices
{
get => devices;
set
{
devices = value;
this.RaiseAndSetIfChanged(ref devices, value);
}
}
How can I make a ListBox update when the field of a certain AvaloniaList element changes?
So far I see only one option: to clear and re-fill the collection, but I would like to avoid this.
Recently started studying C#, making a project using AvaloniaUI, ReactiveUI and a MVVM pattern.
The essence of the problem is as follows: there is an AvaloniaList(observable collection), a ListBox is bound to it by binding.
MainWindow.axaml:
<ListBox Items="{Binding Devices}"
SelectedItem="{Binding SelectedDevice}"
SelectionMode="Single, Toggle">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="5">
<TextBlock FontSize="18" Text="{Binding name}" />
<TextBlock Text="{Binding state}" />
<TextBlock Text="{Binding ip}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
ViewModels:
private AvaloniaList<Device>? devices;
public AvaloniaList<Device> Devices
{
get => devices;
set
{
devices = value;
this.RaiseAndSetIfChanged(ref devices, value);
}
}
How can I make a ListBox update when the field of a certain AvaloniaList element changes?
So far I see only one option: to clear and re-fill the collection, but I would like to avoid this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果设备名称更改,则应自动更新,以防设备类也实现 INotifyPropertyChanged
因此,检查“Device”类中的“Name”属性是否具有 RaiseAndSetIfChanged
编辑:
如果您无法更改设备类,则需要确保在更新值时引发设备列表上更改的属性
if a device name changed it should be updated automatically in case the Device class also implement the INotifyPropertyChanged
so check if "Name" property in "Device" Class has RaiseAndSetIfChanged
edit:
if you can't change the class Device you need to make sure to raise property changed on the Devices list when updating a value