如何使用 mvvm 模式对自定义类的 ObservableCollection 的属性进行 TwoWay 绑定?
我有以下类:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的 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.