与XAML中实例化的字符串组合的选择值结合



我有一个字面的组合...

<ComboBox x:Name="DefaultAtt" SelectedValuePath=".">
    <ComboBoxItem IsSelected="True">Name</ComboBoxItem>
    <ComboBoxItem>Command</ComboBoxItem>
    <ComboBoxItem>CommandParameter</ComboBoxItem>
</ComboBox>

,我想绑定以返回所选值。

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

,但我得到了实例的ToString版本...

"System.Windows.Controls.ComboBoxItem: Name"

我尝试了Path=SelectedItem.Content,但这返回null

如何选择值?


答案摘要

这无需设计或运行时错误,但有点冗长,并且有些狡猾

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

这将抛出绑定错误'text'属性在'对象''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

<ComboBox x:Name="DefaultAtt" SelectedValuePath="Text">
<TextBlock Text="{Binding ElementName=DefaultAtt, Path=SelectedValue}" />

这在没有设计或运行时错误

的情况下起作用
<ComboBox x:Name="DefaultAtt" SelectedValuePath="Content">
<TextBlock Text="{Binding ElementName=DefaultAtt, Path=SelectedValue}" />

这无需运行时错误而起作用,但是VS2013给出了警告(无法在类型'对象'的数据上下文中解析属性'content'),并且更详细

<ComboBox x:Name="DefaultAtt" SelectedValuePath=".">
<TextBlock Text="{Binding ElementName=DefaultAtt, Path=SelectedValue.Content}" />

它也没有SelectedValuePath="."

工作

这起作用,但给出了与上述相同的设计时间警告

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

您可以使用其中的任何一个:

<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}"/>

<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}" />

尝试

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

SelectedValuePath属性定义了在绑定过程中要使用的列表项的属性 - 由于您的列表包含类型ComboBoxItem的项目,因此您要绑定到其Content属性!

尝试以下:

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

实际选择value保留comboboxItem,因此您可以使用以下代码获得所需的输出。

最新更新