Binding Text Property in Autocomplete Combobox
could someone help me to solve an issue with combobox behaviour. Here is my combobox control (WPF):
<ComboBox Grid.Row="1" Grid.Column="1" Margin="6,0,6,6" Name="comboBoxRegionTown" IsEditable="True" IsTextSearchEnabled="True" PreviewKeyUp="comboBoxRegionTown_PreviewKeyUp" IsTextSearchCaseSensitive="False" />
The idea is to make it autocomplete (IsEditable="True" IsTextSearchEnabled="True"). So then I typу any text into combobox it shows some results from database.
Here is a code of comboBoxRegionTown_PreviewKeyUp event (C#):
private void comboBoxRegionTown_PreviewKeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
if (!string.IsNullOrEmpty(comboBoxRegionTown.Text))
{
comboBoxRegionTown.ItemsSource = _br.GetQuery(x => x.Name.Contains(comboBoxRegionTown.Text) && x.RegionTypeId == (int)RegionType.Town).ToList();
comboBoxRegionTown.IsDropDownOpen = true;
}
else
{
comboBoxRegionTown.ItemsSource = null;
}
}
So that works fine for me, but then I click to any found item in combobox it puts into ComboBox.Text property the type of my selected object (in this case - Region). Of course I can override ToString() method for my Region object and set there its public property Name and this solution works fine, but I think the best way is to find how to bind selected item into Text property of my combobox. Is there any way to do this?
I've already tryed to ind Text="{Binding Path=Name}" and/or SelectedItem="{Binding Path=Name}" but in these cases just always get empty Text. Please help.
你需要做的是为你的ComboBox设置ItemTemplate
,但是如果你只想显示一个属性,有一个更简单的方法:在ComboBox中设置DisplayMemberPath="Name"
,它会为你生成正确的模板。
上一篇: 如何在字符串索引器数据绑定上实现IDataErrorInfo?
下一篇: 在自动完成组合框中绑定文本属性