Search code examples
c#wpfmvvmdata-bindingcombobox

WPF Binding TextBlock value to display SelectedItem in ComboBox


I have a ComboBox and a couple of TextBlock fields.

I want to display the properties of a SelectedItem from the ComboBox on those Textblock's. Image

So that when I choose one of multiple user's the properties in the TextBlock will update to those of the SelectedItem. I have found an example, although it is using silverlight, and does not work entirely.

        <ComboBox Grid.Row="0"
                  Grid.Column="0"
                  VerticalAlignment="Bottom"
                  VerticalContentAlignment="Center"
                  HorizontalContentAlignment="Left"
                  Margin="0"
                  Height="40"
                  Name="ComboBox" 
                  ItemsSource="{Binding UserModels}" 
                  SelectedItem="{Binding EnteredUserModel, Mode=TwoWay}">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding FirstName}"
                               Style="{StaticResource ResourceKey=ComboBoxItemTextBlock}"/>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
    </Grid>


        <TextBlock Grid.Row="1"
                   Grid.Column="0"
                   Margin="0 10 0 10" >
            <Run Text="{DynamicResource firstName}" />
            <Run Text=": " />
            <Run Text="{Binding ElementName=ComboBox, Path=SelectedItem, UpdateSourceTrigger=PropertyChanged}" />
        </TextBlock>

This is what I've tried. I added Name to the ComboBox so that I can access it's SelectedItem in my TextBlock. I need to get the SelectedItem.firstname, etc. At this stage i can only access the entire objects.

Am I missing some useful binding?


Solution

  • In order to show the FirstName property of the SelectedItem, just use an appropriate property path, i.e. SelectedItem.FirstName:

    <Run Text="{Binding ElementName=ComboBox, Path=SelectedItem.FirstName}" />
    

    or, since SelectedItem is bound to an EnteredUserModel property in your view model:

    <Run Text="{Binding Path=EnteredUserModel.FirstName}" />
    

    Setting UpdateSourceTrigger=PropertyChanged is not necessary. It has no effect in a OneWay Binding.