trickui
trickui

Reputation: 297

Delete all items from listobox

Hi i am try to delete all elements from a list box: this is my simple listbox:

 <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>

But when i try to delete all elements of list box the error is:

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());
        }
    }

Thank!

Upvotes: 1

Views: 1997

Answers (2)

Waleed
Waleed

Reputation: 3145

You should do your binding using 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();

Upvotes: 1

Snowbear
Snowbear

Reputation: 17274

You cannot clear Items collection if you specify it as Binding. You should clear bound collection instead. Don't forget that your source collection should implement INotifyCollectionChanged

Upvotes: 6

Related Questions