当某个 AvaloniaList 元素的字段发生变化时,如何使 ListBox 更新?

发布于 2025-01-14 02:00:12 字数 1087 浏览 4 评论 0原文

最近开始学习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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光匆匆的小流年 2025-01-21 02:00:12

如果设备名称更改,则应自动更新,以防设备类也实现 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文