【问题标题】:Why is ListBox.Items.IsReadOnly=true? (F#/Silverlight)为什么 ListBox.Items.IsReadOnly=true? (F#/银光)
【发布时间】:2010-11-30 20:44:26
【问题描述】:

我正在尝试从我创建的 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()

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

【问题讨论】:

    标签: silverlight f# listbox


    【解决方案1】:

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

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

    【讨论】:

    • 我会尝试...这很奇怪,因为在 C# 中 Items.Remove/Items.RemoveAt 似乎工作:stackoverflow.com/questions/1400091/…
    • @Mike - 同意这很奇怪,但我对 F# 不够熟悉,无法说出它为什么不同。
    • 通过创建一个新的 ObservableCollection,将其分配为我的 ListBox 上的 ItemsSource,然后操作它而不是 Items 来实现这一点。仍然不确定为什么 Items 是只读的,但是嘿,这行得通。谢谢。
    【解决方案2】:

    以下代码对我来说很好用:

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

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

    【讨论】:

    • 除了分配ListBox的一些属性(高度等),没有。
    猜你喜欢
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    • 2010-12-02
    • 2011-05-30
    相关资源
    最近更新 更多