清除 WPF 中的组合框

问题描述 投票:0回答:4

如何清除 WPF 中的组合框?我已经尝试过这段代码:

 private void btClear1_Click(object sender, RoutedEventArgs e)
    {

        txtID.Text = String.Empty;
        this.cbType.SelectedItem = -1;
    }
c# wpf combobox
4个回答
5
投票

cbType.SelectedItem = -1
清除选择
cbType.Items.Clear()
清除所有项目


3
投票

要清除选择,请设置

SelectedIndex
而不是
SelectedItem

cboType.SelectedIndex = -1;

您也可以设置

SelectedItem
SelectedValue
,但将其更改为
null
而不是 -1(这些指向一个对象而不是整数)。

cboType.SelectedItem = null;

3
投票

您可以通过在XAML页面中绑定来重置组合框。

例如,在 XAML 页面的组合框字段中:

text={Binding viewmodelobject Name.property Name}

然后在

ViewModelPage

viewmodelobject Name.property Name="";

1
投票

彻底清空盒子里的物品
对于 Google 员工来说,由于标题具有误导性,如果我们谈论的是清除盒子中的物品,我看到几个答案说要使用

cbType.Items.Clear()
。这取决于物品的装载方式。您可以将它们硬编码到 XAML 中,在运行时通过函数动态添加它们,使用某种类型的数据绑定和/或将它们加载到
.ItemSource
。除了后一种情况之外,它适用于所有情况。

例如,当您使用

.ItemSource
通过数据表的
ComboBox
加载
DefaultView
时,您不能简单地执行
cbType.Items.Clear()
。由于填充下拉列表的方法未包含在问题中,因此我认为当您设置
.ItemSource
时,您必须执行以下操作:

cbType.ItemsSource = null;

相反。否则,如果您尝试

cbType.Items.Clear()
,您将得到:

Operation is not valid while ItemSource is in use. Access and modify 
elements with ItemsControl.ItemsSource instead


清除所选项目
我回去看到OP的评论,说希望清除选择,而不是框。为此,其他答案成立:

cbType.SelectedIndex = -1;  
cbType.Text = "";  // I've found the first line does this for me, as far as appearances, but found other postings saying it's necessary - maybe they were using the property and it wasn't getting cleared, otherwise
© www.soinside.com 2019 - 2024. All rights reserved.