2012-12-04 89 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="..."/>