[WPF] 編集可能なComboBoxのTextが消える問題
編集可能なComboBox (IsEditable="True")のItemsSorceを変更したときに、ItemsSorceから現在の項目が消えた場合にTextも消滅してしまう問題です。
あくまでもComboBoxのメニュー(DropDown)は「選択もできるよ!」のつもりなのに、メニューから消えるとTextも消えてしまいます。
<ComboBox IsEditable="True" ItemsSorce="{Binding Items}" Text="{Binding Item}" />
class vm { public string Item { get; set; } public IEnumerable<string> Items { get; set; } = new []{ "みかん", "りんご", "ぶどう" }; }
例えば ItemsSorce :[みかん、りんご、ぶどう] 、 Text:[みかん] の状態で、
ItemsSorce を [りんご、ぶどう] に変更すると Text が空欄になってしまうわけです。
イベント的にSelectionChangedしか無いのでこんな感じで対応しました。
public IEnumerable ItemsSource { get; set; } void OnSelectionChanged( object sender, SelectionChangedEventArgs e ) { var comboBox = (ComboBox)sender; if( this.ItemsSource != comboBox.ItemsSource ) { this.ItemsSource = comboBox.ItemsSource; if( comboBox.SelectedItem == null ) { var text = comboBox.Text; comboBox.Dispatcher.BeginInvoke( (Action)( () => { comboBox.Text = text; } ) ); } } }
comboBox.Dispatcher.BeginInvoke がミソで、一旦comboBox.Textは空欄になってしまいますが再度入力し直す動きなります。
SelectedItemは先にNullになるけど、Textはまだ残っている不思議
参考:
ikriv.com