1

I'm binding a List<string> to my ListBox in WPF using MVVM

At the moment I have

<ListBox ItemsSource="{Binding FileContents}"></ListBox>

File Contents in my ViewModel is simply

public List<string> FileContents {get;set;}

And the FileContents values are set in the constructor of the ViewModel, as such there is no need to worry about INotifyProperty

Everything works fine so far. I can see the list displayed in my ListBox as desired.

Now I need to provide a template! This is where it goes wrong

<ListBox ItemsSource="{Binding FileContents}">
     <ListBox.ItemTemplate>
          <DataTemplate>
              <TextBox Text="{Binding}" />
           </DataTemplate>
     </ListBox.ItemTemplate>
 </ListBox>

This is where it all goes wrong! My understanding is that I only need to do <TextBox Text = "{Binding}" because the ListBox is already bound to the List<string> property (called FileContents)

However, when I run the above Visual Studio gives me

The application is in break mode

If I update the code to

<TextBox Text = "Some String Value"

then it works fine

I don't understand what I've done wrong.

0

2 Answers 2

2

Set the Mode of the Binding to OneWay:

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

The default binding mode for the Text property of a TextBox is TwoWay but this won't work when you bind to a string in a List<string>.

Sign up to request clarification or add additional context in comments.

Comments

2

Binding to a string directly is only possible one way. This means you are only able to bind read only like

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

or

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

The reason is simple: Changing the string means you are removing and adding an item to your list. This is simply not possible by changing the string in a TextBox.

A solution is to wrap the content in a class like

public class FileContent
{
    public string Content { get; set; }
}

and bind to a list of List<FileContent> by using <TextBox Text="{Binding Content}"/> as template.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.