Search code examples
wpfmvvmbindingcomboboxtextbox

Binding properties of selected object in combobox to TextBox in WPF


I'm using MVVM to load text files and to show their content.

Model

MyFile.cs has a Name and Text // Implements the INotifyPropertyChanged

MyFileRepository.cs // collection of my loaded files

ViewModel

OpenFileCommand to load a file and add it to the _filerepository object

FileCollection that's bound to the View

View

Button to fire the OpenCommand

ComboBox to show the names of the loaded files

TextBox to show the content of selected file in combobx

<Button Name="OpenFile" Command="{Binding OpenFileCommand}">
<ComboBox  Name="FilesList" ItemsSource="{Binding Path=FileCollection}" DisplayMemberPath="Name" />
<TextBox Name="FileContent" Text="{Binding the Text of selected file in combobx "/>

How to bind the Text property of MyFile selected in combobx to the TextBox?


Solution

  • The easiest approach would be element binding:

    <TextBox Name="FileContent"
             Text="{Binding SelectedItem.Text,ElementName=FilesList} />
    

    So that's binding to the Text property of the SelectedItem in your FilesList ComboBox, which (if everything's wired up the way I think it is) is of type MyFile.