2010-07-30 105 views
36

我有一个ComboBox和ComboBox.IsEditable属性设置为True,以使ComboBox同时充当TextBox和下拉列表。但是,当ComboBox数据绑定时,输入自定义文本不会导致将新项目添加到数据绑定集合中。WPF可编辑组合框

例如,如果我在与不包含值“Joe”的人员列表绑定的组合框中输入“Joe”,则值“Joe”不会被添加到自动下拉列表。

处理这个问题的最佳方法是什么?

回答

3

我会在LostFocus事件中处理它。

在这里你可以检查SelectedItem是否为空。如果是这样,请将Text的值添加到绑定列表中,并将SelectedItem设置为新项目。

在XAML:

<ComboBox Name="_list" LostFocus="LostFocus" IsEditable="True"/> 

在后台代码:

希望这有助于:)

+0

您可能还想在DropDownOpened事件中执行此操作。 – Taudris 2011-03-11 21:33:05

3

我的建议是使用MVVM的方法,并结合您的ComboBox.Text到你的ViewModel的一些TextProperty。 (只需向视图中添加一个字符串属性即可实现) 然后,您可以在此属性的setter中处理输入,并将该新项添加到列表中,无论在视图中“提交”哪种方式。 AFAIK没有开箱即用的机制来将新项目添加到数据源中,无论如何您都必须自己完成项目生成。

或者,您可以绑定 - SelectedItem和ComboBox的文本 - 以避免在用户输入已知项目的情况下进行查找。但是那个部分对于回答你的问题可能不那么重要。

68

这里获得的行为,你想有一个基本的MVVM兼容的方式:

MainWindow.xaml

<Window x:Class="WpfApplication1.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <StackPanel> 
     <ComboBox Margin="30,5,30,5" 
        IsEditable="True" 
        ItemsSource="{Binding Items}" 
        SelectedItem="{Binding SelectedItem}" 
        Text="{Binding NewItem, UpdateSourceTrigger=LostFocus}"/> 
     <TextBox Margin="30,5,30,5" /> 
    </StackPanel> 
</Window> 

MainWindow.cs

public partial class MainWindow : Window, INotifyPropertyChanged 
{ 
    private string _selectedItem; 

    private ObservableCollection<string> _items = new ObservableCollection<string>() 
    { 
     "One", 
     "Two", 
     "Three", 
     "Four", 
     "Five", 
    }; 

    public MainWindow() 
    { 
     InitializeComponent(); 
     this.DataContext = this; 
    } 

    public IEnumerable Items 
    { 
     get { return _items; } 
    } 

    public string SelectedItem 
    { 
     get { return _selectedItem; } 
     set 
     { 
      _selectedItem = value; 
      OnPropertyChanged("SelectedItem"); 
     } 
    } 

    public string NewItem 
    { 
     set 
     { 
      if (SelectedItem != null) 
      { 
       return; 
      } 
      if (!string.IsNullOrEmpty(value)) 
      { 
       _items.Add(value); 
       SelectedItem = value; 
      } 
     } 
    } 

    protected void OnPropertyChanged(string propertyName) 
    { 
     var handler = this.PropertyChanged; 
     if (handler != null) 
     { 
      handler(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 
} 

我不得不把窗口中的其他控制,我已经设置TextUpdateSourceTrigger属性绑定到LostFocus。如果窗口中没有其他控件,那么Combobox将永远不会失去焦点。

我改变了更新模式,因为默认的更新模式是Propertychanged,它会为每个击键添加一个新的项目。

E.G.如果您输入文本“窗口”,则会将以下内容添加到您的收藏中:

W 
Wi 
Win 
Wind 
Windo 
Window 
+4

我不得不添加get {return SelectedItem; }的NewItem属性为我工作。 – 2012-11-19 15:01:17

+0

这太棒了!完美的作品。 :) – Kokos 2014-12-18 21:56:45