名前を含むコンボボックスを取得しました。私の目標は、テキストボックスで文字列を検索し、この文字列で始まる名前がコンボボックスに表示されるようにすることです。
例えば:
私のコンボボックスには次のアイテムが含まれています:
「マーク」、「アリック」、「マイケル」
ユーザーがテキストボックスに「Mi
」と入力すると、コンボボックスには「Michael
」のみが表示されます。
PS ボタンはありません。テキストボックスとコンボボックスのみ。
名前を含むコンボボックスを取得しました。私の目標は、テキストボックスで文字列を検索し、この文字列で始まる名前がコンボボックスに表示されるようにすることです。
例えば:
私のコンボボックスには次のアイテムが含まれています:
「マーク」、「アリック」、「マイケル」
ユーザーがテキストボックスに「Mi
」と入力すると、コンボボックスには「Michael
」のみが表示されます。
PS ボタンはありません。テキストボックスとコンボボックスのみ。
バインドを使用してコンボボックスに入力する場合は、テキスト プロパティを作成してテキスト ボックスにバインドする必要があります (双方向モード バインディング)。
このプロパティのセッターでは、ビューの以前のセットアップ フィルタリングのフィルタリング条件を変更するだけです。
http://msdn.microsoft.com/en-us/library/system.windows.data.collectionviewsource.getdefaultview.aspx
また、場合によっては、ビューではなくコレクションをフィルタリングしたい場合があります。しかし、決めるのはあなたです。
例を用意しました。
この例では、2 つの追加アセンブリを使用します。
XAML ファイル:
<Window x:Class="ComboBoxFilter.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"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
>
<Grid>
<StackPanel>
<TextBox Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="TextChanged">
<i:InvokeCommandAction Command="{Binding SearchItems}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
<ComboBox ItemsSource="{Binding MySourceData}" />
</StackPanel>
</Grid>
</Window>
ViewModel クラス:
class MainViewModel : NotificationObject
{
public MainViewModel()
{
_myItems.Add("aaa");
_myItems.Add("abb");
_myItems.Add("aab");
_myItems.Add("bbb");
_myItems.Add("bcc");
_myItems.Add("bbc");
SearchItems = new DelegateCommand(this.OnSearchItems);
}
private string _searchText;
public string SearchText
{
get { return _searchText; }
set { _searchText = value; RaisePropertyChanged(() => SearchText); }
}
private ICollectionView _mySourceData;
public ICollectionView MySourceData
{
get { return CollectionViewSource.GetDefaultView(_myItems); }
}
private List<string> _myItems = new List<string>();
public ICommand SearchItems { get; private set; }
private void OnSearchItems()
{
MySourceData.Filter = (o) => { return string.IsNullOrEmpty(SearchText) ? true : (o as string).StartsWith(SearchText); };
}
}
ctor でウィンドウ DataContext を設定することを忘れないでください。
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainViewModel();
}
追加のアセンブリ (ComboBoxFilter.zip) を含むすべてのソリューションを次に示します。