2013-07-27 106 views
0

我想要一個綁定到集合的複選框列表。所以當選擇選項時,它們被添加到列表中---當選項被取消時,它們被刪除。如何將枚舉ItemsControl綁定到WPF中的集合?

已經嘗試了很多方法,但未能解決此問題。

模型

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> 

回答

1

聲明一個視圖模式l對於天氣類型:

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>