如何在 WPF 中将通用生成的复选框与枚举标志绑定?

问题描述 投票:0回答:1

我们有一个人可以拥有多种技能(力量、智力和运气)。在我们的 WPF 应用程序中,我们希望将这些技能绑定到复选框。当一个人的列表中有这些技能时,应该选中复选框:

enter image description here

Person 类和枚举:

public class Person
{
    public string Name { get; set; }    

    public List<SkillsEnum> Skills { get; set; } // <-- The skills of the user
}

public enum SkillsEnum // <-- All available skills
{ 
    Strength,
    Intelligence,
    Luck
}

我们的视图模型:

public class InitAppViewModel : ViewModelBase
{    
    public Person CurrentPerson { get; set; }

    public IEnumerable<string> AvailableSkills
    {
        get { return Enum.GetNames(typeof(SkillsEnum)).ToList(); }
    }

    public InitAppViewModel()
    {
        CurrentPerson = new Person() { Name = "Foo", Skills = new List<SkillsEnum> { SkillsEnum.Luck, SkillsEnum.Intelligence } };
    }
}

相应的 XAML 标记:

<ItemsControl x:Name="CurrentPerson_Skills" ItemsSource="{Binding AvailableSkills}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding}" IsChecked="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl}, Path=DataContext.CurrentPerson.Skills, Converter={StaticResource SkillToBoolConverter}}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

转换器:

public class SkillToBoolConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // conversion code here which returns a boolean
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

我们如何将复选框元素的枚举值和人员的技能传递到 SkillToBoolConverter 中,以便我们可以验证技能并返回 true/false 以便选中/取消选中复选框?

wpf data-binding wpf-controls checkboxlist
1个回答
0
投票

你可以这样做: 在 xaml 中:

<ItemsControl x:Name="CurrentPerson_Skills" ItemsSource="{Binding PersonSkills}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding SkillName}" IsChecked="{Binding IsChecked}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

在视图模型中:

PersonSkills = new ObservableCollection<SelectedItem>();
foreach (var skill in Enum.GetNames(typeof(SkillsEnum)))
{
    PersonSkills.Add(new SelectedItem(skill));
}

所选项目:

public class SelectedItem
{
    bool _isChecked;
    public SelectedItem(string skillName)
    {
        SkillName = skillName;
    }

    public bool IsChecked
    {
        get { return _isChecked; }
        set
        {
            //RaisePropertyChanged
        }
    }

    public string SkillName { get; set; }
}
© www.soinside.com 2019 - 2024. All rights reserved.