WPF combobox with image in case of null value
I would like to have a combobox in WPF whose items are of type string (like the default). The only difference is that I want to display an image (error) if the string is x:null. Anyone an idea how I can create an itemtemplate or style to display an image in the case of a null (or empty) string and the string in all other cases in the co开发者_开发问答mbobox.
Thanks!
-- Carsten
Here is an example that uses an ItemTemplate
and a DataTrigger
to only show an image if the item is null:
<Grid>
<Grid.Resources>
<x:Array x:Key="sampleData" Type="sys:String">
<sys:String>abc</sys:String>
<sys:String>def</sys:String>
<sys:String>ghi</sys:String>
<x:Null/>
</x:Array>
</Grid.Resources>
<StackPanel>
<ComboBox ItemsSource="{StaticResource sampleData}" Text="abc">
<ComboBox.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding}"/>
<Image x:Name="errorImage" Source="http://thecybershadow.net/misc/stackoverflow.png" Visibility="Collapsed"/>
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding}" Value="{x:Null}">
<Setter TargetName="errorImage" Property="Visibility" Value="Visible"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
</Grid>
and it looks like this where the fourth null item is displayed as a stack overflow image:
Ok, here is the remaining piece in the style combobox (edit a copy of it and look for ContenPresenter and replace with this):
<Grid>
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" IsHitTestVisible="false" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" Content="{TemplateBinding SelectionBoxItem}" ContentStringFormat="{TemplateBinding SelectionBoxItemStringFormat}" ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}" ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}"/>
<Image x:Name="errorImage" Source="/Autodesk.UtilityDesign.Electric.UI;component/Themes/Images/Error.ico" Visibility="Collapsed" Width="16"/>
</Grid>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="SelectedItem" Value="{x:Null}">
<Setter TargetName="errorImage" Property="Visibility" Value="Visible"/>
</Trigger>
精彩评论