2012-12-04 38 views
3

我有ComboBox自定义ItemTemplate带自定义项目模板文本的wpf组合框

<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

+0

您可以发布您放入ComboBox的物品类型代码吗?我想我还没有完全理解这个问题。 – Spontifixus

+0

我的对象来自于Canvas – takayoshi

+0

所以'Designs'属性是某种'IEnumerable '?你想要显示的文本来自哪里? – Spontifixus

回答

1

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

-1

文本块添加到DataTemplate中,并将其绑定 或矩形 编辑添加Contentpersenter: 好像我没有得到你想要完成的任务,

+0

看看我的更新。它做这件事吗? – takayoshi

0

我通过雷伯恩斯一个好办法找到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="..."/>