c# - WPF,如何在选择后重置组合框

标签 c# wpf xaml combobox

我想在每次选择后将组合框重置为默认文本值。这个问题问的很好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,但它保持为空。我希望文本回到它最初所说的内容,但我没有运气。感谢您的帮助。

最佳答案

获得所选项目后,您可以将 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 的内部逻辑取代,该逻辑在您的事件处理程序完成后运行。

关于c# - WPF,如何在选择后重置组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28596244/

相关文章:

c# - 使 Wcf 服务集成 WindowsAuthentication

c# - 在 asp.net 中存储用户相关数据的最佳位置在哪里?

c# - 使用 LINQ 将 double[][][] 初始化为 double[1][2][3]

c# - 如何从UserControl1 WPF MVVM中的按钮将数据从一个UserControl1传递到UserControl2

c# - 为什么 GUI 在 Web 浏览器导航和加载时卡住?

c# - WPF win8平板电脑模式键盘隐藏屏幕底部的项目

c# - 在 WPF MVVM 中使用 ReactiveUI 获取属性更改的先验值

c# - VisualStateGroup的ViewModel方法事件

c# - 无边框窗口无法正确最大化

wpf - 限制其容器内的 WPF 元素宽度