Search code examples
mvvmdata-bindinguwpuwp-xamlobservablecollection

UWP ObservableCollection<string> does not bind to TextBox


In XAML, I have an ItemsControl binded to an ObservableCollection<string>.
Inside it as ItemControl.ItemTemplate, a TextBox binded to the string.

<ItemsControl ItemsSource="{x:Bind ViewModel.MyNames, Mode=TwoWay}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
                <TextBox Text="{Binding Mode=TwoWay}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
public ObservableCollection<string> MyNames = new ObservableCollection<string> {"aa", "bb", "cc" };

If I edit any text box I receive the Error:

Error      
Cannot save value from target back to source. Binding: Path='' DataItem='Windows.Foundation.IReference`1<String>';
target element is 'Windows.UI.Xaml.Controls.TextBox' (Name='null');
target property is 'Text' (type 'String')      

How do I link the text box to the string value? While respecting MVVM pattern of course. x:Bind I don't know if it can bind to the default value given by ItemsSource.


Solution

  • A string is immutable and cannot be modified.

    If you want to just display the values from the ObservableCollection<string> in the TextBoxes, you could use a OneWay binding:

    <TextBox Text="{Binding Mode=OneWay}"/>
    

    If you want to be able to edit the values, you need to replace the ObservableCollection<string> with an ObservableCollection<YourType> where YourType is a custom type which has a string property that can be set to a new value:

    public class ViewModel
    {
        public ObservableCollection<CustomType> MyNames = 
            new ObservableCollection<CustomType> 
            { 
                new CustomType { Value ="aa" },
                new CustomType { Value ="bb" },
                new CustomType { Value ="cc" }
            };
    }
    
    public class CustomType
    {
        public string Value { get; set; }
    }
    

    XAML:

    <TextBox Text="{Binding Value}"/>