【问题标题】:How to add a fixed value in a listbox containing binded items如何在包含绑定项的列表框中添加固定值
【发布时间】:2012-07-02 15:33:35
【问题描述】:

我有一个提供变量数据集的可枚举值。这些值是在用户运行时生成的。

这些值绑定到 ListBox 的 ItemsSource

public IEnumerable<string> Items
{
  get { return list; } // list is here a dummy; it does not actually exists
}

listbox.SetBinding(ListBox.ItemsSourceProperty, new Binding { Source = Items });

现在我想在开头添加一个固定项目。但是例如lb.Items.Add("abc"); 将中断运行时。插入方法也一样。

// listbox.Items.Add("abc");
// listbox.Items.Insert(0, "abc");

如何在开头添加固定项?

【问题讨论】:

  • break = 你得到一个异常?

标签: c# binding listbox


【解决方案1】:

如果您绑定到IEnumerable&lt;string&gt;,则可以使用Concat

listbox.SetBinding(ListBox.ItemsSourceProperty, 
  new Binding { Source = new[] { "abc" }.Concat(Items) }); 

同样,如果您要绑定的是 List&lt;string&gt; - 在构建后使用 Insert 在头部添加固定项目。

【讨论】:

  • 太棒了。谢谢,不知道会这么简单:)
  • 如果我想使用new Binding("Items") 创建绑定,您是否也知道该怎么做。
  • 如果您的意思类似于Binding(string, object, string) constructor,那么您应该能够将new[] { "abc" }.Concat(Items) 作为第二个参数传递。不过,您可能需要在末尾添加 .ToArray() - 不先尝试一下,看看是否可行。
  • 啊我想我明白了 - 你想把字符串 "Items" 解析为表单上的属性吗?我会问一个单独的问题:)
  • 是的,这就是我想做的。项目应该是 PropertyPath,而不是我的第一种方法中的 Source。 :)
猜你喜欢
  • 2015-04-04
  • 2018-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-31
  • 1970-01-01
  • 2020-08-30
相关资源
最近更新 更多