0

I'm using a ComboBox defined by:

    <ComboBox Grid.Column="2" Height="29" HorizontalAlignment="Left" Margin="137,192,0,0" Name="componentsComboBox" VerticalAlignment="Top" Width="224" 
              IsEditable="True"
              TextSearch.TextPath="Name">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}" />
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox> 

..to display a list of objects by their "Name" properties. I'm observing the following behaviors:

  1. Click an item in the dropdown, and componentsComboBox.SelectedValue (and .SelectedItem) correspond to the clicked item. OK!
  2. Start typing the name of an item, autocomplete fills in as you type, .SelectedValue (and .SelectedItem) correspond to the autocompleted item. GREAT!
  3. Start typing the name of an item, autocomplete fills in as you type, hit delete to truncate to only what you have actually typed, .SelectedValue and .SelectedItem STILL correspond to the autocompleted item. NO! BAD WPF! BAD!
  4. Similar behavior to 3 if you delete characters from the end of the textbox portion

In essence, if I have a List containing two objects defined by, e.g.,

{ new Component() { Name = "COMPONENT1"}, 
  new Component() { Name = "COMPONENT2"} }

I want the values:

  • COMPONENT1
  • COMPONENT2

to appear in the drop-down portion, and if the user enters "COMP" I would like to recognize that they have entered a new value, but as it stands right the control makes it look like they selected COMPONENT1.

What am I missing here?

4

2 回答 2

0

您可以通过将 IsEditable 和 IsReadOnly 属性分别设置为 True 和 False 在 WPF 中轻松完成此操作。

参考:http: //msdn.microsoft.com/en-us/library/system.windows.controls.combobox.iseditable.aspx

例如,如何允许用户在 WPF 的 ComboBox 中编辑文本?

<Window x:Class="LearnWPF.EditableComboBox.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="LearnWPF.EditableComboBox" Height="300" Width="300" 
    > 
  <Window.Resources> 
    <XmlDataProvider x:Key="items" XPath="//item"> 
      <x:XData> 
        <items xmlns=""> 
          <item>01</item> 
          <item>02</item> 
          <item>03</item> 
        </items> 
      </x:XData> 
    </XmlDataProvider> 
  </Window.Resources> 
    <Grid> 
      <ComboBox IsEditable="True" DataContext="{StaticResource items}" 
                ItemsSource="{Binding}"/> 
    </Grid> 
</Window>
于 2012-08-07T05:48:13.963 回答
0

我今天经历了这种行为,并同意从表面上看,这似乎是一个错误。挖掘得更深一些,但会发现一些灰色区域。

我认为这里发生的是,每次更新文本框时,控件都会运行前缀匹配算法,而不管导致文本框更新的击键。所以当你删除文本的自动完成部分时,前缀匹配算法仍然匹配控件的ItemsSource中的一个项目;控件不会试图推断最终用户刚刚删除了自动完成的部分,因此算法不应该运行。

回复:您对 akjoshi 回复的评论,当您删除“2”时,在组合框的文本框中只留下“0”,前缀匹配算法正确匹配“01”项目。

我使用的解决方法是仅绑定到 ComboBox 的 Text 属性并以此构建所有视图模型逻辑。SelectedItem、SelectedIndex 和 SelectedValue 根本没有绑定。

于 2014-10-21T21:12:29.767 回答