这是我当前填充组合框的方式。有什么方法可以使用这样的列表,但还可以在项目的左侧添加一个小的颜色预览框?
private void PantsColor_ComboBox_Loaded(object sender, RoutedEventArgs e)
{
List<string> data = new List<string>();
data.Add("Blue");
data.Add("Red");
data.Add("Green");
data.Add("Orange");
data.Add("Pink");
data.Add("Purple");
var pantsColorComboBox = sender as ComboBox;
pantsColorComboBox.ItemsSource = data;
pantsColorComboBox.SelectedIndex = 0;
}
答案 0 :(得分:1)
可以在ComboBox.ItemTemplate中添加项目左侧的颜色预览框:
private void ColorComboBoxLoaded(object sender, RoutedEventArgs e)
{
var cbo = sender as ComboBox;
if (cbo == null)
return;
cbo.ItemsSource = new List<string> { "Blue", "Red", "Green", "Orange", "Pink", "Purple" };
}
<ComboBox SelectedIndex="0"
Loaded="ColorComboBoxLoaded">
<ComboBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Border Background="{Binding}" Height="20" Width="24" Margin="2"/>
<TextBlock Grid.Column="1" Margin="5,0" VerticalAlignment="Center" Text="{Binding}"/>
</Grid>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
结果:
请注意,可以在xaml中设置SelectedIndex。还要注意,即使背景设置为string
,也仍然可以正确应用,因为有一个内置的转换器可以根据颜色名称(或十六进制ARGB代码)创建画笔。
<ComboBox SelectedIndex="0">
<ComboBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Border Background="{Binding}" Height="20" Width="24" Margin="2"/>
<TextBlock Grid.Column="1" Margin="5,0" VerticalAlignment="Center" Text="{Binding}"/>
</Grid>
</DataTemplate>
</ComboBox.ItemTemplate>
<ComboBox.Items>
<system:String>Blue</system:String>
<system:String>Red</system:String>
<system:String>Green</system:String>
<system:String>Orange</system:String>
<system:String>Pink</system:String>
<system:String>Purple</system:String>
</ComboBox.Items>
</ComboBox>
答案 1 :(得分:0)
您需要对组合框项目使用Datatemplate。
$RAX
您的项源将被修改为词典。
<ComboBox x:Name="pantsColorComboBox" Height="30" Width="200">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Width="20" Height="20" Background="{Binding Key}"></TextBlock>
<TextBlock Text="{Binding Value}"></TextBlock>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>