ComboBox是经常使用的一个控件,有时候需要自定义。
多数时候需要对下拉框中的样式进行自定义,或添加功能。
下面的例子实现了一个以下2个功能
1.下拉框中每一项都有一个删除按钮,点击删除,从下拉框中移除。
2.能够在textbox中直接输入,输入后显示到下拉框中。
所使用到的属性主要有以下几个:
1.ItemSource,这个主要用来获取或设置用于生成ItemsControl 的内容的集合。
2.DisplayMemberPath,获取或设置源对象上某个值的路径,是定义描述如何显示数据对象的默认模板的一种简便方式。
3.IsReadOnly,获取或设置启用仅限选择模式的值,在此模式中,可选择但不可编辑组合框中的内容。
4.IsEditable,获取或设置一个值,该值指示启用或禁用 ComboBox 的文本框中的文本编辑。
5.Text,获取或设置当前选定项的文本。当 IsEditable 属性为 true 时,设置此属性会将输入的初始文本放置到文本框中。
6.SelectedItem,获取或设置当前选择中的第一个项,或者在选择为空时返回 null。
7.ItemTemplate,获取或设置用于显示每个项的 DataTemplate。
以上属性,再配合后台代码处理保存和删除的功能,一个特定的ComboBox就完成了。
其中有一点需要注意,在ItemTemplate时,使用了一个Grid,定义了2列,第一列放了一个TextBlock,第二列放了一个Button。如果Grid不设定Width属性,Button会紧紧靠着前面的文字,而不是靠右对齐。通过设置Grid的宽度和ComboBox的ActualWidth相同就可以了。首先,为ComboBox命名,然后通过Element 绑定,就可以解决次问题了。
具体代码如下:
<ComboBox Name="editCobox" ItemsSource="{Binding Source={StaticResource typeVMList},Path=TypeItems}" DisplayMemberPath="Name"
IsReadOnly="False" IsEditable="True" Text="{Binding EventType,UpdateSourceTrigger=LostFocus}" SelectedItem="{Binding SelectedTypeViewMode,Mode=TwoWay}">
<ComboBox.ItemTemplate>
<DataTemplate >
<Grid Width="{Binding ElementName=editCobox, Path=ActualWidth}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Name}"></TextBlock>
<Button Grid.Column="1" HorizontalAlignment="Right" Width="20" Command="{Binding DelTypeCmd}" Margin="0,0,-4,0">
<Button.Template>
<ControlTemplate>
<Border Name="ClearBorder" Background="{DynamicResource NormalBrush}" BorderBrush="{DynamicResource NormalBorderBrush}" BorderThickness="0">
<Path x:Name="X" HorizontalAlignment="Center" Stroke="{DynamicResource GlyphBrush}" VerticalAlignment="Center">
<Path.Data>
<PathGeometry>
<PathGeometry.Figures>
<PathFigure StartPoint="0,0">
<PathFigure.Segments>
<LineSegment Point="5,5"/>
</PathFigure.Segments>
</PathFigure>
<PathFigure StartPoint="0,5">
<PathFigure.Segments>
<LineSegment Point="5,0"/>
</PathFigure.Segments>
</PathFigure>
</PathGeometry.Figures>
</PathGeometry>
</Path.Data>
</Path>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="Button.IsMouseOver" Value="true">
<Setter TargetName="ClearBorder" Property="Background" Value="{DynamicResource DarkBrush}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Button.Template>
</Button>
</Grid>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>