WPF Combobox loses Text after Selection

馋奶兔 提交于 2019-12-24 00:32:37

问题


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:

and the filtering like this

How can I prevent the combobox from overwriting my custom text with a ""?

Update:

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>

回答1:


remove OnSelectionChanged

add the following to the RoleKeyElementVM

public override string ToString()
{
    return this.Key;
}

better?



来源:https://stackoverflow.com/questions/47812405/wpf-combobox-loses-text-after-selection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!