C# 清除WPF中的组合框

C# 清除WPF中的组合框,c#,wpf,combobox,C#,Wpf,Combobox,如何清除WPF中的组合框?我尝试过以下代码: private void btClear1_Click(object sender, RoutedEventArgs e) { txtID.Text = String.Empty; this.cbType.SelectedItem = -1; } cbTypion.SelectedItem=-1清除所选内容 cbType.Items.Clear()清除所有项目清除选择设置SelectedIndex

如何清除WPF中的组合框?我尝试过以下代码:

 private void btClear1_Click(object sender, RoutedEventArgs e)
    {

        txtID.Text = String.Empty;
        this.cbType.SelectedItem = -1;
    }

cbTypion.SelectedItem=-1
清除所选内容
cbType.Items.Clear()
清除所有项目清除选择设置
SelectedIndex
而不是
SelectedItem

cboType.SelectedIndex = -1;
您也可以设置
SelectedItem
SelectedValue
,但将其更改为
null
,而不是-1(它们指向的对象不是整数)


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

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

text={Binding viewmodelobject Name.property Name}
然后在
ViewModelPage
中:

viewmodelobject Name.property Name="";

完全清除方框项目
对于谷歌用户来说,由于标题具有误导性,如果我们谈论的是从框中清除项目,我看到几个答案是使用
cbType.items.Clear()
。这取决于项目的加载方式。您可以将它们硬编码到XAML中,在运行时使用函数动态添加它们,使用某种类型的数据绑定和/或将它们加载到
.ItemSource
。除后一种情况外,它将适用于所有情况

例如,当您使用
.ItemSource
通过数据表的
默认视图加载
组合框时,您不能简单地执行
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

按“删除所有项目”中的方式清除,或按“清除所选内容”中的方式清除?您可以将SelectedIndex=-1替换为selectedItem。无论如何,@Fred的答案是最正确的;)关于上面Fred的评论,这实际上取决于是否通过添加
ComboBoxItem
来填充
ComboxBox
——无论是在XAML中还是动态填充,还是通过绑定到
ItemsSource
来填充。如果使用后者,则无法执行
cbType.Items.Clear()
——您会得到:
操作在使用ItemSource时无效。改为使用ItemsControl.ItemsSource访问和修改元素。
。首先,问题真的需要包括如何将项目填充到框中。相关-我并不想迂腐,但我很好奇您选择的名称
cbType
。对我来说,这意味着该值是一个类型,而不是一个组合框。是否有我不知道的WPF或.Net约定?当我尝试此方法时,我得到:对象引用未设置为对象的实例。在cbType_SelectionChanged–@user2631662中,在尝试对所选组合框执行操作之前,将您的
SelectionChanged
事件更改为检查nullitem@user2631662我怀疑在您的
SelectionChanged
事件中,您正在调用组合框的
SelectedItem
上的方法(可能是
cboType.SelectedItem.ToString()
)。如果未选择任何内容,这将抛出一个null引用,因此只需在该方法顶部添加一个条件,说明if(cboType.SelectedItem==null)return;这实际上取决于
组合框是通过在XAML中或动态添加
组合框项来填充的,还是通过绑定到
项源来填充的。如果使用后者,则无法执行
cbType.Items.Clear()
--您得到:
操作在使用ItemSource时无效。请改为使用ItemsControl.ItemsSource访问和修改元素。
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