WPF组合框选择后丢失文本 [英] WPF Combobox loses Text after Selection
问题描述
我想要一个可搜索的组合框。当我在其中输入内容时,项目列表将被过滤。 OnTextChanged可以做到这一点。第二部分是,在组合框列表中,所有项目均以其简短描述显示,但是当我选择一个项目时,我希望显示键。在SelectionChanged上应该这样做,但是每次我选择一个项目时,组合框输入字段都会被覆盖。
I would like to have a searchable combobox. When I type something into it, the itemlist gets filtered. OnTextChanged does this quite fine. The second part is, inside the comboboxlist all the items are displayed with their shortdescription, but when I select an item, I want the key to be displayed. On SelectionChanged should do that, but everytime I select an item, the combobox input field gets overwritten with "".
private void OnTextChanged(object sender, TextChangedEventArgs e)
{
ItemSource = new ObservableCollection<RoleKeyElementVM>(DataSource.Where(x => x.ShortDescription.Contains(RoleKeyCombobox.Text) || x.Key.ToString() == RoleKeyCombobox.Text));
RoleKeyCombobox.ItemsSource = ItemSource;
}
private void OnSelectionChanged(object sender, EventArgs e)
{
RoleKeyElementVM SelectedItem = RoleKeyCombobox.SelectedItem as RoleKeyElementVM;
if(SelectedItem != null)
RoleKeyCombobox.Text = SelectedItem.Key.ToString();
}
选择应如下所示:
The selection should look like this:
以及类似的过滤器
如何防止组合框用覆盖我的自定义文本?
How can I prevent the combobox from overwriting my custom text with a ""?
更新:
我们正在讨论的组合框:
The combobox we are talking about:
<ComboBox
Name="RoleKeyCombobox"
Margin="5" Grid.Column="2" Grid.Row="0"
IsEditable="True"
IsSynchronizedWithCurrentItem="False"
TextBoxBase.TextChanged="OnTextChanged"
SelectionChanged="OnSelectionChanged">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ShortDescription}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
推荐答案
删除OnSelectionChanged
remove OnSelectionChanged
将以下内容添加到RoleKeyElementVM
add the following to the RoleKeyElementVM
public override string ToString()
{
return this.Key;
}
更好吗?
这篇关于WPF组合框选择后丢失文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!