如何删除所有ListBox项目?

Nan*_* HE 31 c# wpf listbox

我创建了两个RadioButton(重量和高度).我会在两个类别之间切换.但是它们共享相同的ListBox控制器(listBox1和listBox2).

有没有什么好方法可以更简单地清除所有ListBox项?我找不到ListBox的removeAll().我不喜欢我在这里发布的复杂的多行样式.

private void Weight_Click(object sender, RoutedEventArgs e)
    {
        // switch between the radioButton "Weith" and "Height"
        // Clear all the items first
        listBox1.Items.Remove("foot"); 
        listBox1.Items.Remove("inch");
        listBox1.Items.Remove("meter");
        listBox2.Items.Remove("foot");
        listBox2.Items.Remove("inch");
        listBox2.Items.Remove("meter");

        // Add source units items for listBox1
        listBox1.Items.Add("kilogram");
        listBox1.Items.Add("pound");

        // Add target units items for listBox2
        listBox2.Items.Add("kilogram");
        listBox2.Items.Add("pound");
    }

    private void Height_Click(object sender, RoutedEventArgs e)
    {
        // switch between the radioButton "Weith" and "Height"
        // Clear all the items first
        listBox1.Items.Remove("kilogram");
        listBox1.Items.Remove("pound");
        listBox2.Items.Remove("kilogram");
        listBox2.Items.Remove("pound");

        // Add source units items for listBox1
        listBox1.Items.Add("foot");
        listBox1.Items.Add("inch");
        listBox1.Items.Add("meter");

        // Add target units items for listBox2
        listBox2.Items.Add("foot");
        listBox2.Items.Add("inch");
        listBox2.Items.Add("meter");
    }
Run Code Online (Sandbox Code Playgroud)

bal*_*dre 79

与Winform和Webform方式不一样?

listBox1.Items.Clear();
Run Code Online (Sandbox Code Playgroud)

  • 这归结为社区责任感.考虑一下:一个八岁的孩子拿着一把装满枪的枪(不是玩具)来找我.他显然没有注意到他指向的地方.他问我怎么拍它.在这种情况下,"只需拉动此触发器"就是一个糟糕的答案.更好的答案是解释枪支安全问题.对于一个八岁的孩子来说,最好的答案可能就是拿走枪去找他的父母.这里的利害关系要低得多,但原则是相同的:**鼓励写得不好的代码会造成真正的损害和真正的痛苦.**这对我们所有人来说都是一个真正的代价. (16认同)
  • 问题是"有没有什么好方法可以更简单地清除所有ListBox项目?" 这是一个更简单的问题,它有一个简单的答案!马特回答的问题是"我在这里做对了吗?" (3认同)

Mat*_*ing 8

我认为将listBoxes实际绑定到数据源会更好,因为看起来你正在为每个列表框添加相同的元素.一个简单的例子是这样的:

    private List<String> _weight = new List<string>() { "kilogram", "pound" };
    private List<String> _height = new List<string>() { "foot", "inch", "meter" };

    public Window1()
    {            
        InitializeComponent();
    }        

    private void Weight_Click(object sender, RoutedEventArgs e)
    {
        listBox1.ItemsSource = _weight;
        listBox2.ItemsSource = _weight;
    }

    private void Height_Click(object sender, RoutedEventArgs e)
    {
        listBox1.ItemsSource = _height;
        listBox2.ItemsSource = _height;
    }
Run Code Online (Sandbox Code Playgroud)