简体   繁体   中英

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.

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:

<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.". 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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM