WPF自定义项模板文本的ComboBox

4

我有一个带有自定义ItemTemplateComboBox

<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试图将矩形绘制成下拉框的文本。如何为此模板设置“文本”。我指的是表示所选项目并在选择项目时写入下拉框的字符串或控件。

换句话说,我想做到这一点:

enter image description here

但现在我得到了这个:

enter image description here


请问您能否发布一下放入ComboBox的项的类型的代码?我认为我还没有完全理解这个问题。 - Spontifixus
我的对象派生自Canvas。 - takayoshi
名称属性。据我所知,Canvas也有名称属性。 - takayoshi
我想在下拉列表中显示矩形,并将名称属性作为文本显示。 - takayoshi
1
现在你的问题已经清楚了。我暂时没有时间提供详细的答案,但是你需要为整个 ComboBox 创建一个控件模板,在焦点集中时显示字符串“Design”。请记住,这不是 Windows 组合框的默认行为 - 因此用户可能不会期望这样的结果。 - Spontifixus
显示剩余2条评论
3个回答

1

尝试使用TextBlock设置SelectionBoxItemTemplate。 似乎SelectionBoxItemTemplate是只读的。因此,另一种方法是覆盖ItemContainerStyle.Template。示例


0

我发现Ray Burns提供的this解决方案是一个不错的方法。你可以定义两个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="..."/>

-1
将Textblock添加到datatemplate并绑定它, 或在矩形上添加Contentpersenter。 编辑: 看起来我没有理解你想要实现什么,

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接