c# - 从列表框中删除所有项目

标签 c# windows-phone-7

您好,我正在尝试从列表框中删除所有元素: 这是我的简单列表框:

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

谢谢!

最佳答案

如果将 Items 集合指定为 Binding,则无法清除它。您应该改为清除绑定(bind)集合。不要忘记您的源集合应该实现 INotifyCollectionChanged

关于c# - 从列表框中删除所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6315190/

相关文章:

c# - 以正确的方式从 Datagridview 插入数据。时间:2019-03-17 标签:c#Mysql

由于导入 C++ DLL,C# ShowDialog() 抛出错误

c# - 在 Silverlight/WP7 应用程序中使用 MultiTouchBehavior 时,如何以编程方式查找缩放、旋转和平移值?

silverlight - 加载事件未完全加载

c# - 简单的隔离存储问题

c# - 当调用者期望特定的构造函数签名时使用构造函数注入(inject)

c# - 当只有图像名称保存在数据库中时,如何在 RDLC 报告中显示图像?

c# - AutoFixture,创建电子邮件地址列表

c# - 使用 WebRequest 发布

windows-phone-7 - 键盘处于事件状态时 ScrollViewer 不会向上滚动