我想要一个绑定到集合的复选框列表。因此,当选择选项时,它们会被添加到列表中 - 当取消选择选项时,它们将被删除。
尝试过多种方法,但未能解决这个问题。
模型
public enum WeatherType
{
Rainy,
Sunny,
Cloudy,
Windy
}
视图模型
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>
答案 0 :(得分:1)
声明天气类型的视图模型:
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>