如何在WPF中将枚举ItemsControl绑定到集合

本文关键字:ItemsControl 绑定 集合 枚举 WPF | 更新日期: 2023-09-27 18:25:12

我想要一个绑定到集合的复选框列表。因此,当选项被选中时,它们会被添加到列表中——当选项被取消选择时,它们就会被删除。

尝试了许多方法,但未能解决此问题。

型号

 public enum WeatherType
 {
    Rainy,
    Sunny,
    Cloudy,
    Windy
 }

ViewModel

public class WeatherViewModel : INotifyPropertyChanged
{
    public ObservableCollection<WeatherType> WeatherTypes {get;set;}
    ...
}

XAML

 <ObjectDataProvider x:Key="weather"
            MethodName="GetValues"
            ObjectType="{x:Type sys:Enum}">
    <ObjectDataProvider.MethodParameters>
    <x:Type TypeName="business:WeatherType" />
    </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
...
<ItemsControl Grid.Row="4"
      Grid.Column="1"
      ItemsSource="{Binding Source={StaticResource weather}}">
<ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
    <StackPanel />
    </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
    <DataTemplate>
    <StackPanel Orientation="Horizontal">
        <CheckBox Content="{Binding}" />
    </StackPanel>
    </DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>

如何在WPF中将枚举ItemsControl绑定到集合

声明天气类型的视图模型:

public class WeatherTypeViewModel
{
    public WeatherType WeatherType { get; set; }
    public bool IsChecked { get; set; }
}

更改您的视图模型如下:

public class WeatherViewModel : INotifyPropertyChanged
{
    public ObservableCollection<WeatherTypeViewModel> WeatherTypes {get;set;}
    ...
}

和视图-像这样:

<ItemsControl Grid.Row="4"
      Grid.Column="1"
      ItemsSource="{Binding WeatherTypes}">
<ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
    <StackPanel />
    </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
    <DataTemplate>
    <StackPanel Orientation="Horizontal">
        <CheckBox Content="{Binding WeatherType}" IsChecked="{Binding IsChecked}"/>
    </StackPanel>
    </DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>