我想在每次选择后将组合框重置为默认文本值。这问题问得很好here,但这个解决方案对我来说根本不起作用。对我有意义的解决方案是将SelectedIndex设置为-1并重置Text,如下所示
MainWindow.xaml
<ComboBox Name="combobox" SelectionChanged="ComboBox_SelectionChanged" IsEditable="True" IsReadOnly="True" Text="My Default Text">
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Setter Property="Background" Value="Blue"/>
<Setter Property="BorderBrush" Value="Blue"/>
<Setter Property="BorderThickness" Value="0"/>
</Style>
</ComboBox.ItemContainerStyle>
<ComboBoxItem Name="selection0">selection0</ComboBoxItem>
<ComboBoxItem Name="selection1">selection1</ComboBoxItem>
<ComboBoxItem Name="selection2">selection2</ComboBoxItem>
<ComboBoxItem Name="selection3">selection3</ComboBoxItem>
<ComboBoxItem Name="selection4">selection4</ComboBoxItem>
</ComboBox>
MainWindow.xaml.cs
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string name = selectedItem.Name;
if (selectedItem != null)
{
MessageBox.Show(string.Format(string));
//This does set the combobox to empty, but no text is added.
this.combobox.SelectedIndex = -1;
this.combobox.Text = "My Default Text";
}
}
SelectedIndex成功转到-1,但它保持为空。我希望文本回到原来的说法,但我没有运气。任何帮助表示赞赏。
答案 0 :(得分:2)
获得所选项目后,您可以将ComboBox
重置为默认状态,但必须在单独的Dispatcher
消息中执行此操作:
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (this.combobox.SelectedItem != null)
{
MessageBox.Show(this.combobox.SelectedItem.ToString());
}
Action a = () => this.combobox.Text = "My Default Text";
Dispatcher.BeginInvoke(a);
}
如果您尝试在同一消息中执行此操作,那么您的更改将被WPF的内部逻辑取代,该逻辑在您的事件处理程序完成后运行。