0

我想要一个绑定到集合的复选框列表。So when options are selected, they are added to the list --- when options are deselected, they get removed.

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

模型

 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>
4

1 回答 1

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>
于 2013-07-27T07:24:49.507 回答