Xaml文件:
<ListBox Name="lbTasteSet" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ItemsSource="{Binding TasteSet}" Style="{StaticResource MultipleToggleButtonList}"
SelectionMode="Multiple">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding GetTasteCommand}"
CommandParameter="{Binding ElementName=lbTasteSet}"></i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" ItemHeight="30" ItemWidth="60"></WrapPanel>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
Xaml中用到的Style:因为ToggleButton相当于ListBoxItem的Content,这时要使togglebutton的IsSelected属性与ListBox的SelectedItem的IsSelect属性关联则需要在Style中设置下划线所示Setter
<Style TargetType="ListBox" x:Key="MultipleToggleButtonList">
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="ListBoxItem">
<Setter Property="IsSelected" Value="{Binding Path=IsSelected,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Border Background="Transparent" Margin="{TemplateBinding Padding}">
<telerik:RadToggleButton Content="{Binding Path=Taste.Name}"
IsChecked="{Binding Path=IsSelected,Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent}}"> </telerik:RadToggleButton>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Setter.Value>
</Setter>
</Style>
ViewModel:用到了(lanmuda)表达式
/// <summary>
/// 获取选择的口味
/// </summary>
public void ExecuteGetTaste(ListBox lb)
{
//TasteItemViewModel model = lb.SelectedItem as TasteItemViewModel;
List<Taste> selectedTastes= this.TasteSet.Where(i => i.IsSelected == true).Select(i => i.Taste).ToList();
selectedTastes.Distinct();
string strTaste = "";
foreach (var item in selectedTastes)
{
strTaste += "["+item.Name+"]";
}
this.DishTaste = strTaste;
}