简体   繁体   中英

How to bind string property to TextBox within ListBox

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.

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

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.

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