“未找到项目”的wpf组合框事件

时间:2014-10-06 09:30:09

标签: wpf combobox

我可以知道文本是否与列表中没有项目兼容

<ComboBox IsEditable="True" ItemSource="..."/>

有一个事件或属性可以确定TextSearch

是否找不到任何项目

1 个答案:

答案 0 :(得分: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();
    }
}

这里是ViewModel:

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;
    }

}

我希望它有所帮助。

相关问题