简体   繁体   English

wpf ComboBox所选项目显示不同的文本,然后在下拉菜单中显示项目

[英]wpf ComboBox Selected Item Displaying different text then item in drop down

I have a ComboBox that has a list of colors that the user can pick from. 我有一个ComboBox ,其中包含用户可以选择的颜色列表。 When the user clicks on a list of colors with the colors name and a small picture of the color is displayed for each item. 当用户单击带有颜色名称的颜色列表时,将为每个项目显示该颜色的小图片。 This part works correctly. 这部分正常工作。 The part I can't get to work is once a item has been selected, for example if the user choses red, the ComboBox will say "Color[Red]" where I just want it to display Red. 一旦选择了某个项目,我就无法工作的部分,例如,如果用户选择红色,则ComboBox会在我只希望它显示红色的地方说“ Color [Red]”。

XAML XAML

<ComboBox x:Name="mycbox" IsEditable="True" Background="#FFE5E5E5" HorizontalAlignment="Left" Margin="21,133,0,0" VerticalAlignment="Top" Width="82">      
     <ComboBox.ItemTemplate>
         <DataTemplate>
             <StackPanel Orientation="Horizontal">
                  <Rectangle Fill="{Binding Name}" Width="16" Height="16" Margin="0,2,5,2"/>
                  <TextBlock Text="{Binding Name}"/>
              </StackPanel>
          </DataTemplate>
       </ComboBox.ItemTemplate>                                
 </ComboBox>

Code Behind 背后的代码

private List<Color> colors = new List<Color>() {  Red, Green, Blue, Cyan, Magenta, Yellow, Orange, Purple};

mycbox.ItemSource = colors;

Here is an example of what my combo box items look like, to use as a reference. 这是我的组合框项目外观的示例,可以用作参考。

how can I get the ComboBox.SelectedItem to just "Red" and not "Color[Red]"? 如何将ComboBox.SelectedItem设置为“ Red”而不是“ Color [Red]”?

Set the TextSearch.TextPath property of the ComboBox to "Name". ComboBoxTextSearch.TextPath属性设置为“名称”。

<ComboBox x:Name="mycbox" IsEditable="True" 
          TextSearch.TextPath="Name" 
          Background="#FFE5E5E5" HorizontalAlignment="Left" VerticalAlignment="Top" Width="82">

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

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