WPF datagrid XML binding displaying multiple Items

2019-08-18 07:49发布

问题:

I have a DataGrid which is as follows::

<wpfkit:DataGrid AutoGenerateColumns="False"
       ItemsSource="{Binding}"
       Width="Auto"
       FrozenColumnCount="2"
       SelectionMode="Extended"
       CanUserAddRows="False"
       x:Name="CommonPEGrid"
       Loaded="CommonPEGrid_Loaded">
    <wpfkit:DataGrid.DataContext>
        <XmlDataProvider Source="PE.xml" XPath="/Rows/Row"></XmlDataProvider>
    </wpfkit:DataGrid.DataContext>
</wpfkit:DataGrid>

I am binding it from XML to DataGrid. My XML is as follows::

<Rows>
<Row Id="1">
  <Devices>
    <Device>Device 1</Device>
    <Device>Device 2</Device>
 </Devices>
</Row>

<Row Id="2">
  <Devices>
    <Device>Device 3</Device>
    <Device>Device 4</Device>
  </Devices>
</Row>

I have a DataTemplate for a cell in DataGrid defined as follows ::

<DataTemplate x:Key="MethodDefault">
    <ComboBox Margin="5" Height="25" ItemsSource="{Binding XPath=./Devices}"  SelectedIndex="0" 
                       >
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding XPath=./Device}"></TextBlock>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>
</DataTemplate>

The problem is it always displays only 1 Device i.e first device in combobox. I want to display all Devices in a dropdown. I dont know how to iterate through them. I had thought that ComboBox will automatically iterate which is not the case. Please help me!!

回答1:

I could figure out the answer. I am posting it assuming it helps someone !!

<ComboBox  ItemsSource="{Binding XPath=.//Devices}"  SelectedIndex="0" >

</ComboBox>