Two-way binding an ObservableCollection<string> to WPF DataGrid
I've been tying different things / reading up on this issue for awhile now and have not yet found an answer. Hopefully you guys can help.
I have an observablecollection of type string. I want to bind this collection to a datagrid and be able to edit/delete/add to the collection. Here is my xaml:
开发者_Go百科<DataGrid ItemsSource="{Binding Movies.Titles}" CanUserDeleteRows="True" CanUserAddRows="True" Height="300">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=DataContext, RelativeSource={RelativeSource Self}}"/>
</DataGrid.Columns>
</DataGrid>
The same observablecollection is also bound to a listbox. I want to be able to edit the collection using the datagrid method (above) and see the changes/edits in the listbox. The delete/add is working correctly, but when I edit a string inside a grid cell and it loses focus, the string goes back to what it originally was and never gets updated.
Thanks a lot for any help / suggestions.
Wow, I went to do this yesterday and was stuck with a DataGrid that would add a new line for my ObservableCollection. After research, I realized why. Strings and immutable.
I found this question and unfortunately it didn't have an answer. So I can't leave this empty of an answer.
So here are the answers I found:
DataGrid cannot update a string collection by adding, editing, or removing strings.
I found a workaround to wrap the string in a StringWrapper object. Here it is.
public class StringWrapper { public string Text { get; set; } }
I didn't like either answer.
The original question asker, moncadad, looks like he wants a one column DataGrid. He probably just wants to add and remove strings from an ObservableCollection without a lot of code. Edit probably isn't too important since that can be done by delete and add again.
I ended up doing this myself with a reusable usercontrol I made called StringListBox.
A ListBox for strings that supports add and delete
Basically the idea is to create the look of a DataGrid with a Label, a ListBox, a TextBox and an Add button and since this is a control, it has to work with ObservableObject or List in one control.
This give you Add and Delete. I doesn't provide edit.
Hope this helps the next guy.
Actually it works, you should just use
Mode=OneWay
in your binding.
I hope this helps!
精彩评论