gpt4 book ai didi

c# - WPF 绑定(bind)到子集合

转载 作者:行者123 更新时间:2023-11-30 17:46:11 26 4
gpt4 key购买 nike

我有以下实体:

public class User
{
public User()
{
Roles = new ObservableCollection<Role>();
}

public int UserId { get; set; }
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }

public virtual ICollection<Role> Roles { get; set; }
}

public class Role
{
public int RoleId { get; set; }
public string Name { get; set; }

public virtual User User { get; set; }
}

使用这个 ViewModel:

public class UserManagerViewModel : ObservableObject
{
public ObservableCollection<Role> AllRoles { get; set; }
public UserViewModel()
{
AllRoles = new ObservableCollection<Role>(RoleRepository.GetAll());
}

private User _selectedUser;
public User SelectedUser
{
get { return _selectedUser; }
set
{
if (_selectedUser != value)
{
_selectedUser = value;
RaisePropertyChanged();
}
}
}

...
}

我想以下列方式(或任何类似方式)显示 SelectedUser 角色:

<Window.DataContext>
<vm:UserManagerViewModel/>
</Window.DataContext>
<ListBox ItemsSource="{Binding AllRoles}">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Name}" IsChecked="{Binding ???}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

我需要如何设置 CheckBoxIsChecked 属性,以便它代表 SelectedUser 角色?

最佳答案

假设您想“检查”SelectedUser 拥有的角色。

首先我们回答这个问题,“这取决于什么数据?”答案很简单,取决于角色本身,所以我们这样写:

<CheckBox Content="{Binding Name}" IsChecked="{Binding .}"/>

现在很明显,这不是 bool 值;所以我们需要为它编写一个转换器来检查集合。我们可以在这里做一个 MultiValueConverter(如@Moji 的回答),但通过依赖属性公开集合并在创建转换器时绑定(bind)可能更容易。

<Window.Resources>
<local:CollectionContainsConverter Collection="{Binding SelectedUser.Roles}"/>
</Window.Resources>

<CheckBox Content="{Binding Name}" IsChecked="{Binding Path=., Converter={StaticResource CollectionContainsConverter}"/>

和转换器:

public class CollectionContainsConverter : IValueConverter
{
public IEnumerable<object> Collection { get; set; } //This is actually a DP

public object Convert(...)
{
return Collection.Contains(value);
// or possibly, to allow for the Object.Equals override
return Collection.Any(o => o.Equals(value));
}

public object ConvertBack(...)
{
return Binding.DoNothing;
}
}

如果没有对此进行测试,您可能需要使用第二个返回,这样它就不会比较引用,并利用 Object.Equals(或您选择的其他比较器)来确定项目是否在列表中。

关于c# - WPF 绑定(bind)到子集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26490952/

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