C# WPF,选择后如何重置组合框
我想在每次选择后将组合框重置为默认文本值。这个问题问得很好,但这个解决方案对我根本不起作用。对我来说,一个有意义的解决方案是将SelectedIndex设置为-1并重置文本,如下所示 main window.xamlC# WPF,选择后如何重置组合框,c#,wpf,xaml,combobox,C#,Wpf,Xaml,Combobox,我想在每次选择后将组合框重置为默认文本值。这个问题问得很好,但这个解决方案对我根本不起作用。对我来说,一个有意义的解决方案是将SelectedIndex设置为-1并重置文本,如下所示 main window.xaml <ComboBox Name="combobox" SelectionChanged="ComboBox_SelectionChanged" IsEditable="True" IsReadOnly="True" Text="My Default Text">
<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>
SelectedIndex确实成功转到-1,但它保持为空。我希望这篇文章能回到它原来说的,但我运气不好。非常感谢您的帮助。一旦您获得所选项目,您可以将组合框重置为默认状态,但必须在单独的
调度程序中执行此操作
消息:
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的内部逻辑有效地取代,该逻辑在事件处理程序完成后运行。为什么需要执行此操作?:)这个特定的事情,我不想做,但我有一个更大的问题,我正试图解决,这个问题的答案会从逻辑上解决我更大的问题。但为什么会有人这样做是一个合理的问题:)
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);
}