Binding with ObservableCollection <string>
I'm trying to do something very simple: I want to show an ObservableCollection in an ItemsControl. I also want the user to be able to edit the rows in the ObservableCollection.
My view model is pretty simple:
public class MainViewModel : ViewModelBase
{
public ObservableCollection<string> Values { get; set; }
public MainViewModel()
{
Values = new ObservableCollection<string> { "foo", "bar" };
}
}
In my opinion, I define a DataTemplate for my ItemsControl to display a textbox inside each item, no problem:
<ItemsControl ItemsSource="{Binding Values}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type sys:String}">
<TextBox Text="{Binding Path=., UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Everything seems to be running smoothly, I can see the contents of my ObservableCollection in my opinion. However, when I edit the text in the textbox my ObservableCollection is not updated, the values โโremain the same.
The only workaround I've found for this to work is to create a class:
public class StringWrapper
{
public string Value { get; set; }
}
Then I change the type of my ObservableCollection to ObservableCollection<StringWrapper>
and in my DataTemplate I bind the Text property of my TextBox to a value. It works, but it's ugly.
So my question is, is there a way to bind the ObservableCollection to the ItemsControl and be able to update the values?
source to share
Except that it is handled directly by the list control, I doubt it can be done. The templated element in yours ItemsControl
only has access to the instance string
, not the actual collection. And since it string
is immutable, it is a dead end, there is no way to track changes to the parent.
source to share