繁体   English   中英

wpf combobox与自定义itemtemplate文本

[英]wpf combobox with custom itemtemplate text

我有自定义ItemTemplate ComboBox

<ComboBox Height="20" Width="200" 
          SelectedItem="{Binding Path=SelectedDesign}"
          ItemsSource="{Binding Path=Designs}" HorizontalAlignment="Left" 
          ScrollViewer.CanContentScroll="False">

    <ComboBox.ItemTemplate>
        <DataTemplate DataType="{x:Type formdesign:FormDesignContainer}">
            <Rectangle Width="200" Height="100">
                <Rectangle.Fill>
                    <ImageBrush ImageSource="{Binding Path=ImageThumb}" Stretch="Uniform" />
                </Rectangle.Fill>
            </Rectangle>
        </DataTemplate>
    </ComboBox.ItemTemplate>

</ComboBox>

这很好用。 但是,WPF尝试将矩形绘制为Combobox Text。 如何为此模板设置“文本”。 “text”我指的是表示所选项目的字符串或控件,并在选择项目时写入组合框

换句话说,我想这样做:

在此输入图像描述

但现在我得到了这个

在此输入图像描述

尝试使用TextBlock设置SelectionBoxItemTemplate。 看起来SelectionBoxItemTemplate是只读的。 所以另一种方法是重写ItemContainerStyle.Template。

我发现Ray Burns这个解决方案是一个很好的方法。 您可以为下拉列表中的项目定义两个DataTemplate ,为Combobox显示的所选项目定义另一个。 使用触发器并检查可视树,它决定使用哪一个。

<Window.Resources>    
  <DataTemplate x:Key="NormalItemTemplate" ...>
    ...
  </DataTemplate>

  <DataTemplate x:Key="SelectionBoxTemplate" ...>
    ...
  </DataTemplate>

  <DataTemplate x:Key="CombinedTemplate">
    <ContentPresenter x:Name="Presenter"
       Content="{Binding}"
       ContentTemplate="{StaticResource NormalItemTemplate}" />
    <DataTemplate.Triggers>
      <DataTrigger
        Binding="{Binding RelativeSource={RelativeSource FindAncestor,ComboBoxItem,1}}"
        Value="{x:Null}">
        <Setter TargetName="Presenter" Property="ContentTemplate"
                Value="{StaticResource SelectionBoxTemplate}" />
      </DataTrigger>
    </DataTemplate.Triggers>
  </DataTemplate>

</Window.Resources>

...

<ComboBox
  ItemTemplate="{StaticResource CombinedTemplate}"
  ItemsSource="..."/>

将Textblock添加到datatemplate并绑定它或在矩形上添加Contentpersenter编辑:看起来我没有得到你要完成的任务,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM