ComboBox的xml绑定无法识别SelectedItem

时间:2014-08-28 03:50:27

标签: xml wpf xaml data-binding

我在WPF窗口中绑定XML文档。 xml doc看起来像这样:

<root>
  <common>
    ... more stuff
    <logSeverityLevel>Debug</logSeverityLevel>
    ...
  </common>
  <collections>
    <logSeverityLevels>
      <logSeverityLevel>Debug</logSeverityLevel>
      <logSeverityLevel>Info</logSeverityLevel>
      <logSeverityLevel>Trace</logSeverityLevel>
      <logSeverityLevel>Error</logSeverityLevel>
      <logSeverityLevel>Fatal</logSeverityLevel>
    </logSeverityLevels>
  </collections>
</root>

和绑定:

<WrapPanel FlowDirection="LeftToRight" DataContext="{Binding XPath=/root/common}">

    <DockPanel>
        <TextBlock Text="Log Severity Level : " />
        <ComboBox SelectedItem="{Binding XPath=logSeverityLevel}" ItemsSource="{Binding XPath=/root/collections/logSeverityLevels/*}" />
    </DockPanel>
</WrapPanel>

现在,当我运行该程序时,我可以看到ComboBox正在填充可能的项目。但它没有将Debug设置为所选值。该怎么办?

1 个答案:

答案 0 :(得分:2)

ComboBox设置SelectedValuePathDisplayMemberPath

<ComboBox SelectedIndex="0"
          SelectedValuePath="@logSeverityLevel"
          DisplayMemberPath="@logSeverityLevel" ... />

这是我的例子:

XAML

<Window.Resources>
    <XmlDataProvider x:Key="Data" XPath="Response/Contact">
        <x:XData>
            <Response xmlns="">
                <Contact Name="Bart" />
                <Contact Name="Eric" />
            </Response>
        </x:XData>
    </XmlDataProvider>
</Window.Resources>

<ComboBox SelectedIndex="0"
          SelectedValuePath="@Name"
          DisplayMemberPath="@Name"
          ItemsSource="{Binding Source={StaticResource Data}}"
          Width="100" Height="30"               
          SelectionChanged="ComboBox_SelectionChanged" />

Code behind

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var comboBox = sender as ComboBox;
        MessageBox.Show(comboBox.SelectedValue.ToString());
    }
}

没有SelectedValuePath SelectedValue将为空。