带有自定义 itemtemplate 文本的 wpf 组合框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13698805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
wpf combobox with custom itemtemplate text
提问by takayoshi
I have ComboBoxwith custom ItemTemplate.
我有ComboBox自定义ItemTemplate。
<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>
This works well. However WPF tries to draw rectangle as Combobox Text. How can I set "text" for this template. By "text" I mean string or control which represent selected item and write into combobox when item is selected
这很好用。但是 WPF 尝试将矩形绘制为组合框文本。如何为此模板设置“文本”。“文本”是指代表所选项目并在选择项目时写入组合框的字符串或控件
In other words I'd like to do this:
换句话说,我想这样做:


But now I got this
但现在我得到了这个


采纳答案by aadam
回答by Hossein Narimani Rad
I found thissolution by Ray Burnsa good approach. You can define two DataTemplateone for Items in the drop down list and the other for the selected item which should be shown in the Combobox. The using a trigger and checking the visual tree it decide which one to use.
我发现Ray Burns的这个解决方案是一个很好的方法。您可以为下拉列表中的项目定义两个,另一个为应显示在. 使用触发器并检查可视化树,它决定使用哪个。DataTemplateCombobox
<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="..."/>
回答by ZSH
Add Textblock to the datatemplate and bind it or add Contentpersenter on the rectangle Edit: it seems like i didn't got what you were tring to accomplish ,
将 Textblock 添加到数据模板并绑定它或在矩形上添加 Contentpersenter 编辑:似乎我没有得到你想要完成的事情,

