C# 在 WPF ComboBox 中以编程方式清除选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/627304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 10:51:53  来源:igfitidea点击:

Programmatically Clear Selection in WPF ComboBox

c#wpf

提问by Bob Wintemberg

I have a ComboBox in WPF whose ItemsSource is set to a list programmatically. How would I go about clearing the selection in an event handler? I've tried:

我在 WPF 中有一个 ComboBox,其 ItemsSource 以编程方式设置为列表。我将如何清除事件处理程序中的选择?我试过了:

comboBox.SelectedIndex = -1;
comboBox.SelectedItem = null;
comboBox.SelectedValue = null;
comboBox.SelectedValue = "";

None of them have any effect.

它们都没有任何效果。

采纳答案by laktak

comboBox.SelectedIndex = -1;works for me.

comboBox.SelectedIndex = -1;为我工作。

Are you doing anything else in your event handler? Are you using databinding?

你在你的事件处理程序中做其他事情吗?你在使用数据绑定吗?

回答by configurator

comboBox.SelectedIndex = -1;

Is the way to go. I don't know why it doesn't work for you; perhaps an event handler for SelectedIndexChangedchanges the value?

是要走的路。我不知道为什么它对你不起作用;也许是用于SelectedIndexChanged更改值的事件处理程序?

回答by Andrew Milford

I found that I needed to also add:

我发现我还需要添加:

comboBox.Text = "";

to get the text to clear

清除文本

回答by Shashika

I want to clear the ComboBoxin DropDownClosedevent of another ComboBox. Therefore I used following code inside of first ComboBoxDropDownClosedevent

我想清除ComboBoxDropDownClosed另一事件ComboBox。因此我在第一个ComboBoxDropDownClosed事件中使用了以下代码

private void comboBox1_DropDownClosed(object sender, EventArgs e)
{
  this.comboBox.ItemsSource = null;
}

回答by Juan Hernandez Ortiz

In the following example I show the way it worked for me, this for a ComboBox from a user control:

在下面的示例中,我展示了它对我的工作方式,这适用于来自用户控件的 ComboBox:

Combobox in the usercontrol:

用户控件中的组合框:

<ComboBox x:Name="OFFSE_INI_CMBX" HorizontalAlignment="Left" Margin="26,106,0,0" VerticalAlignment="Top" Height="20" Width="100" DropDownClosed="OFFSE_INI_CMBX_DropDownClosed">
        <ComboBoxItem x:Name="NV" Content="           NV" ToolTip="Sub Command &#10;Tooltip 1" Height="20" Selected="NV_Selected"></ComboBoxItem>
    </ComboBox>

Function that works

有效的功能

private void OFFSE_INI_CMBX_DropDownClosed(object sender, EventArgs e)
    {
        this.OFFSE_INI_CMBX.SelectedIndex = -1;
        this.OFFSE_INI_CMBX.Text = "";
    }