WPF组合框与空值的情况下的图像

时间:2011-02-13 04:22:46

标签: wpf combobox

我想在WPF中有一个组合框,其项目类型为字符串(如默认值)。唯一的区别是,如果字符串是x:null,我想显示图像(错误)。任何人都知道如何创建itemtemplate或样式以在空(或空)字符串的情况下显示图像,并在组合框中的所有其他情况下显示字符串。

谢谢!

- Carsten

2 个答案:

答案 0 :(得分:2)

以下示例使用ItemTemplateDataTrigger仅在项目为空时显示图片:

<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>

它看起来像第四个空项目显示为堆栈溢出图像:

ComboBox with image

答案 1 :(得分:0)

好的,这是样式组合框中的剩余部分(编辑它的副本并查找ContenPresenter并替换为此):

                        <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>