为什么ListBox.Items.IsReadOnly = true? (F#/ Silverlight的)

时间:2010-11-30 20:44:27

标签: silverlight f# listbox

我正在尝试从我创建的ListBox中删除一些对象,并且由于某种原因,ListBox.Items.IsReadOnly为true。

以下调用不起作用:

myListBox.Items.Add("whatever")
myListBox.Items.Add("stuff")
myListBox.Items.Remove("whatever")

我得到一个例外:

{System.InvalidOperationException: Operation not supported on read-only collection.
   at System.Windows.Controls.ItemCollection.RemoveImpl(Object value)
   at System.Windows.Controls.ItemCollection.RemoveInternal(Object value)
   at System.Windows.PresentationFrameworkCollection`1.Remove(T value)

我可以设置ListBox.ItemsSource,但使用.Items要容易得多。我正在创建像这样的ListBox:

let mutable myListBox= new ListBox()

任何想法/建议将不胜感激。感谢。

2 个答案:

答案 0 :(得分:3)

我不确定F#语法,但你应该设置ListBox.ItemsSource。

如果您创建ObservableCollection然后将其设置为ItemsSource,则可以在集合中添加和删除项目,列表框将自动更新。

答案 1 :(得分:2)

以下代码适用于我:

open System.Windows.Controls
let l = ListBox()
l.Items.Add("An item")
l.Items.Add("Another item")
l.Items.Remove("An item")

您是否在创建列表框和尝试添加项目之间做了其他事情?