当我手动创建组合框时,这是没有问题的,但是由于组合框现在由于设置ItemsSource
而自动填充,我不知道如何设置每个ComboBoxItem
的属性。目前,我需要为每个项目设置Selected
行动(一个全局值)和Tag
(每个项目不同的值)。
目前我只定义组合框项的外观:
<ComboBox ItemsSource="{Binding Path=Modules}"
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Height="16" Width="16" Source="{Binding ObjectData.ImageSource}" />
<Label Content="{Binding ObjectData.Label}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
如何设置我提到的属性?注释:这些属性是ComboBoxItem
的。
Modules
是我窗口类的属性:
public ObservableCollection<SelectableObject<Module>> Modules { get; private set; }
您可以在ComboBox的ItemContainerStyle
中设置ComboBoxItem的属性:
<ComboBox ...>
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Setter Property="Tag" Value="{Binding TagValue}"/>
<Setter Property="IsSelected" Value="{Binding Selected}"/>
</Style>
</ComboBox.ItemContainerStyle>
<ComboBox.ItemTemplate>
<DataTemplate>
...
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
当"global" Selected
属性不在项目视图模型中时,你需要显式地设置绑定源,例如通过RelativeSource/FindAncestor
。