问题描述:

I have a literal ComboBox...

<ComboBox x:Name="DefaultAtt" SelectedValuePath=".">

<ComboBoxItem IsSelected="True">Name</ComboBoxItem>

<ComboBoxItem>Command</ComboBoxItem>

<ComboBoxItem>CommandParameter</ComboBoxItem>

</ComboBox>

and I want a binding to return the selected value.

<TextBlock Text="{Binding ElementName=DefaultAtt, Path=SelectedValue}" />

But I get ToString version of the instance...

"System.Windows.Controls.ComboBoxItem: Name"

I tried Path=SelectedItem.Content but this returns null

How do I just select the value?


Summary of Answers

This works without design or runtime errors, but is a bit verbose and heuristically dodgy

 <TextBlock Text="{Binding ElementName=DefaultAtt, Path=Text}" />

This throws a binding error 'Text' property not found on 'object' ''ComboBoxItem'

<ComboBox x:Name="DefaultAtt" SelectedValuePath="Text">

<TextBlock Text="{Binding ElementName=DefaultAtt, Path=SelectedValue}" />

This works without design or runtime errors

<ComboBox x:Name="DefaultAtt" SelectedValuePath="Content">

<TextBlock Text="{Binding ElementName=DefaultAtt, Path=SelectedValue}" />

This works without runtime errors, but VS2013 gives a warning squiggly (Cannot resolve property 'Content' in data context of type 'object') and it is more verbose

<ComboBox x:Name="DefaultAtt" SelectedValuePath=".">

<TextBlock Text="{Binding ElementName=DefaultAtt, Path=SelectedValue.Content}" />

It also works without SelectedValuePath="."

This works but gives the same design time warning as above

<ComboBoxItem>Name</ComboBoxItem>

<TextBlock Text="{Binding ElementName=DefaultAtt, Path=SelectedItem.Content}" />

网友答案:

You can use either of these:

<ComboBox x:Name="DefaultAtt" SelectedValuePath="Content">
    <ComboBoxItem IsSelected="True">Name</ComboBoxItem>
    <ComboBoxItem>Command</ComboBoxItem>
    <ComboBoxItem>CommandParameter</ComboBoxItem>
</ComboBox>
<TextBlock Text="{Binding ElementName=DefaultAtt, Path=SelectedValue}"/>

or

<ComboBox x:Name="DefaultAtt" SelectedValuePath=".">
    <ComboBoxItem IsSelected="True">Name</ComboBoxItem>
    <ComboBoxItem>Command</ComboBoxItem>
    <ComboBoxItem>CommandParameter</ComboBoxItem>
</ComboBox>
<TextBlock Text="{Binding ElementName=DefaultAtt, Path=SelectedValue.Content}" />
网友答案:

Try

<ComboBox x:Name="DefaultAtt" SelectedValuePath="Content">

The SelectedValuePath attribute defines the property of the list item that is to be used during binding - since your list contains items of type ComboBoxItem, you want to bind to their Content property!

网友答案:

Try this:

      <TextBlock Text="{Binding ElementName=DefaultAtt, Path=Text}" />
网友答案:

Actually selectedvalue hold comboboxitem, So you can use below code to get desired output.

相关阅读:
Top