使用SelectedItem将Combobox数据绑定到XML

时间:2012-01-27 18:43:11

标签: wpf xml xaml data-binding

XML:

...
<importMethod selected="true">MethodA</importMethod>
<importMethod>MethodB</importMethod>
<importMethod>MethodC</importMethod>
...

XAML:

<ComboBox Grid.Row="0" Grid.Column="1" 
     DataContext="{Binding Source={StaticResource XmlSettings}}"
     ItemsSource="{Binding XPath=/settings/importMethod}" />

这正常工作并显示xml中的三个元素,它还显示第四个空白选择,即selectedItem。我的问题是如何将selecteditem设置为具有selected="true"的那个?

我也愿意将我的xml重构为更容易绑定的东西。此外,我正在接受有关WPF的书籍建议,我仍然试图解决这个问题。

1 个答案:

答案 0 :(得分:0)

您可以使用IsSelected绑定项目上的ItemContainerStyle,如下所示:

<ComboBox.ItemContainerStyle>
    <Style TargetType="ComboBoxItem">
        <Setter Property="IsSelected" Value="{Binding XPath=@selected}" />
    </Style>
</ComboBox.ItemContainerStyle>