[英]How do I Bind observableCollection of strings to a listBox
I have an observableCollection instance, I'd like to bind it to a list, and give the user the ability to change the strings in this collection directly. 我有一个observableCollection实例,我想将其绑定到一个列表,并使用户能够直接更改此集合中的字符串。
The current implementation is as follows: 当前的实现如下:
class container
{
public OBservableCollection<string> data {get; set;}
public container() { data = new ... }
}
...
var instance = new container();
listBox.ItemsSource = instance.data;
and for the XAML: 对于XAML:
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding}" MinWidth="50"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
When I add any string to that list an error appears, "Two-way binding requires Path or XPath.". 当我将任何字符串添加到该列表时,都会出现错误,“双向绑定需要Path或XPath。”。 I tried the path value to be "."
我尝试将路径值设为“。” since I am targeting the same source value, but the binding failed.
因为我的目标是相同的源值,但是绑定失败。
Please advise, 请指教,
A WPF Binding can not replace an element in a collection. WPF绑定不能替换集合中的元素。
You will have to create a data item class with a string property 您将必须创建一个带有字符串属性的数据项类
class Item
{
public string Text { get; set; }
}
class Container
{
public ObservableCollection<Item> Data { get; set; }
}
that can be two-way bound: 可以双向绑定:
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding Text}" MinWidth="50"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.