简体   繁体   中英

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?

In order to show the FirstName property of the SelectedItem, just use an appropriate property path, ie 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.

You're getting the EnteredUserModel -Object, because that's the selected item of the ComboBox . If you want the displayed text you must bind to the FirstName-Property.

Alternatively you can bind to EnteredUserModel.FirstName in your TextBox

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