2011-06-11 124 views
1

你好我试图删除列表中的所有元素: 这是我的简单列表框:删除listobox所有项目

<ListBox Margin="0,0,-12,0" ItemsSource="{Binding Items}" Name="listbox" > 
       <ListBox.ItemTemplate> 
        <DataTemplate> 
         <StackPanel Orientation="Horizontal" Margin="0,0,0,17" > 


          <!--Replace rectangle with image--> 
          <Image Source="{Binding Img}" /> 
          <StackPanel Width="311"> 
           <TextBlock Text="{Binding Pos}" 
          </StackPanel> 
         </StackPanel> 
        </DataTemplate> 
       </ListBox.ItemTemplate> 
</ListBox> 

但是,当我试图删除列表框中的所有元素的错误是:

A first chance exception of type 'System.InvalidOperationException' occurred in  System.Windows.dll 
System.InvalidOperationException: Operation not supported on read-only collection. 
    at System.Windows.Controls.ItemCollection.ClearImpl() 
    at System.Windows.PresentationFrameworkCollection`1.Clear() 
    at aaaaa.MainPage.Button_Click(Object sender, RoutedEventArgs e) 
    at System.Windows.Controls.Primitives.ButtonBase.OnClick() 
    at System.Windows.Controls.Button.OnClick() 
    at  System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e) 
    at System.Windows.Controls.Control.OnMouseLeftButtonUp(Control ctrl, EventArgs e) 
    at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName) 

private void Button_Click(object sender, RoutedEventArgs e) 
    { 
     try 
     { 
      listbox.Items.Clear(); 
     } 
     catch (Exception ss) { 
      Debug.WriteLine(ss.ToString()); 
     } 
    } 

谢谢!

回答

6

如果将其指定为Binding,则无法清除Items集合。您应该清除绑定收集。不要忘记,你的源集合应实现INotifyCollectionChanged

+0

感谢您的回答你的绑定!有没有任何教程? – trickui 2011-06-11 11:36:51

+0

@trckui,我不能推荐任何。只是一种体验。 *失败更好*。 – Snowbear 2011-06-11 21:26:02

1

你应该这样做使用的ObservableCollection

// this should be level member instance or something like that just to keep a reference to it. 
ObservableCollection<YourClass> itemsSource = new ObservableCollection<YourClass>(); 
// ... Fill you items collection 
listBox.ItemsSource = itemsSource; 

// if you need to clear your list, just use this code 
itemsSouce.Clear();