2014-10-06 32 views

回答

1

找到兼容您可以检查ComboBox上的SelectedItem属性,如果它在更改时为null,则意味着列表中没有匹配。在这里你有一个小的演示它如何工作。

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"> 
<Grid> 
    <ComboBox ItemsSource="{Binding ItemsSource, UpdateSourceTrigger=PropertyChanged}" 
       IsEditable="True" 
       Text="{Binding TypedText, UpdateSourceTrigger=PropertyChanged}" 
       Height="36" 
       VerticalAlignment="Top"/> 
</Grid> 

XAML.cs:

/// <summary> 
/// Interaction logic for MainWindow.xaml 
/// </summary> 
public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
     DataContext = new MainWindowVM(); 
    } 
} 

,这里的视图模型:

public class MainWindowVM : INotifyPropertyChanged 
{ 
    private ObservableCollection<string> _itemsSource; 

    public ObservableCollection<string> ItemsSource 
    { 
     get { return _itemsSource; } 
     set 
     { 
      _itemsSource = value; 
      OnPropertyChanged("ItemsSource"); 
     } 
    } 

    private string _typedText; 

    public string TypedText 
    { 
     get { return _typedText; } 
     set 
     { 
      _typedText = value; 
      OnPropertyChanged("TypedText"); 
      //check if the typed text is contained in the items source list 
      var searchedItem = ItemsSource.FirstOrDefault(item => item.Contains(_typedText)); 
      if (searchedItem == null) 
      { 
       //the item was not found. Do something 
      } 
      else 
      { 
       //do something else 
      } 
     } 
    } 


    public MainWindowVM() 
    { 
     if (ItemsSource == null) 
     { 
      ItemsSource = new ObservableCollection<string>(); 
     } 
     for (int i = 0; i < 25; i++) 
     { 
      ItemsSource.Add("text" + i); 
     } 
    } 


    public event PropertyChangedEventHandler PropertyChanged; 
    protected virtual void OnPropertyChanged(string propertyName) 
    { 
     PropertyChangedEventHandler handler = PropertyChanged; 
     if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); 
    } 
    protected bool SetField<T>(ref T field, T value, string propertyName) 
    { 
     if (EqualityComparer<T>.Default.Equals(field, value)) return false; 
     field = value; 
     OnPropertyChanged(propertyName); 
     return true; 
    } 

} 

我希望它能帮助。

+0

谢谢,但我无法更新我的属性输入。 我需要知道项目是否存在文本插入到组合框时 – mordechai 2014-10-06 10:40:03

+0

好的,我已经更新了答案,以便您可以检查输入的文本是否包含在项目源列表中,并根据该视图中的操作来决定模型部分。这是你想要达到的目标吗? – 2014-10-06 14:36:07