如何使用 mvvm 模式对自定义类的 ObservableCollection 的属性进行 TwoWay 绑定?

发布于 2024-10-10 05:40:14 字数 1033 浏览 10 评论 0原文

我有以下类:

public class UserGroup
{
   public string GroupName { get; set; }
   public bool IsIntheGroup{ get; set; }
}

我想将 UserGroup 项目的 ObservableCollection 绑定到包含集合中每个项目的复选框的列表框,并且根据 UserGroup 的 IsIntheGroup 属性检查该复选框。在我的 ViewModel 中,我创建了 UserGroup 类的 ObservableCollection:

public ObservableCollection<UserGroup> Groups { get; set; }

并从我的数据库模型加载其内容(UserGroup 的实例)

我在视图中使用了以下代码:

<ListBox ItemsSource="{Binding Groups, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}">
   <ListBox.ItemTemplate>
      <DataTemplate>
         <StackPanel Orientation="Horizontal">
            <CheckBox IsChecked="{Binding IsIntheGroup, Mode=TwoWay}"/>
            <TextBlock Text="{Binding GroupName}" />
         </StackPanel>
      </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

问题是当用户选中/取消选中复选框时,我没有收到通知在列表中,所以我的双向绑定失败...

在这种情况下如何进行双向绑定?

I have the following class:

public class UserGroup
{
   public string GroupName { get; set; }
   public bool IsIntheGroup{ get; set; }
}

I want to bind an ObservableCollection of UserGroup items to listbox containing checkbox’s for each item in the collection and the checkbox is cheked based on the IsIntheGroup property of the UserGroup. In my ViewModel I made an ObservableCollection of the UserGroup class:

public ObservableCollection<UserGroup> Groups { get; set; }

and loaded its contents (instances of UserGroup) from my database model

I used the following code in my view:

<ListBox ItemsSource="{Binding Groups, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}">
   <ListBox.ItemTemplate>
      <DataTemplate>
         <StackPanel Orientation="Horizontal">
            <CheckBox IsChecked="{Binding IsIntheGroup, Mode=TwoWay}"/>
            <TextBlock Text="{Binding GroupName}" />
         </StackPanel>
      </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

The problem is I am not notified when the user checks/unchecks a check box in the list so my two way binding failed…

How do I do a two way binding in such a case?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

风月客 2024-10-17 05:40:14

您的 UserGroup 类应该实现 INotifyPropertyChanged,并且该类的每个属性都应该在其设置器中调用 PropertyChanged 事件。 ObservableCollection 只会通知 UI 集合中的添加或删除,而不会通知集合中每个单独实例的属性更改。

Your UserGroup class should implement INotifyPropertyChanged, and each property of that class should invoke the PropertyChanged event in their setters. ObservableCollection will only notify the UI of additions of removals from the collection, and not property changes of each individual instance in the collection.

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