绑定到在xaml中实例化的字符串ComboBox的SelectedValue

时间:2016-12-14 07:43:29

标签: c# wpf visual-studio-2013 data-binding

我有一个文字的ComboBox ......

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

这会引发绑定错误&#39; Text&#39;在&#39; object&#39;上找不到的属性&#39;&#39; ComboBoxItem&#39;

<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会发出警告(无法解析属性&#39;内容&#39;在类型&#39;对象&#39; 的数据上下文中)更详细

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

4 个答案:

答案 0 :(得分:0)

您可以使用以下任何一种:

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

答案 1 :(得分:0)

尝试

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

SelectedValuePath属性定义了绑定期间要使用的列表项的属性 - 因为列表包含ComboBoxItem类型的项,所以要绑定到它们的Content属性!

答案 2 :(得分:0)

试试这个:

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

答案 3 :(得分:0)

实际上选择值保持组合框,因此您可以使用下面的代码来获得所需的输出。

相关问题