使用DataGridTemplateColumn将数据网格数据绑定到XML

时间:2010-11-04 06:26:30

标签: wpf datagrid combobox datatemplate xml-binding

我有一个像这样的XML ::

<?xml version="1.0" encoding="utf-8" ?>
<Rows>
  <Row Id="1">
     <Devices>
       <Device DeviceId="123">Device 1</Device>
       <Device DeviceId="abcd" >Device 2</Device>
     </Devices>
    <Methods>
       <Method>Method 1</Method>
       <Method>Method 2</Method>
     </Methods>      
</Row>

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

我必须将上面的XML DataBind绑定到DataGrid。

我的DataGrid如下:

       <wpfkit:DataGrid AutoGenerateColumns="False" DataContext="{Binding Grid}"
               ItemsSource="{Binding Path=Elements[Row]}"
               Width="Auto"
               FrozenColumnCount="2"
               SelectionMode="Extended"
               CanUserAddRows="False"
               x:Name="CommonPEGrid"
               Loaded="CommonPEGrid_Loaded">
           </wpfkit:DataGrid>

我关联DataContext的代码如下::我在代码后面创建了一些模板列,并将它们与DataTemplate相关联。

public class MainViewModel : ViewModelBase
{
    public MainViewModel()
    {
        Grid = XElement.Load("PE.xml");  
    }

    public XElement Grid
    {
        get;
        set;
    }       
}

我的代码隐藏如下:::

  public partial class MainView : Window
 {
    DataGrid dg;

    public MainView()
    {
        InitializeComponent();
    }

    private void CommonPEGrid_Loaded(object sender, RoutedEventArgs e)
    {
        dg = sender as DataGrid;

        DataGridTemplateColumn column = null;

        column = new DataGridTemplateColumn();
        column.Header = "Device";
        column.CellTemplate = this.FindResource("DeviceDefault") as DataTemplate;
        dg.Columns.Add(column);

        column = new DataGridTemplateColumn();
        column.Header = "Commands";
        column.CellTemplate = this.FindResource("MethodDefault") as DataTemplate;
        dg.Columns.Add(column);
    }

}

现在我不知道如何使用DataTemplate在ComboBox中显示XML中的元素。它给了我很多错误:::组合框项目总是空的:( :(。我哪里错了。专家请指导我!!!我的代码如下::

 <DataTemplate x:Key="DeviceDefault">
       <ComboBox ItemsSource="{Binding XPath=Devices}"  SelectedIndex="0"  TextSearch.TextPath="Value" >
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Width="auto" FontSize="9" FontWeight="2"  Height="auto" Margin="2" Text="{Binding Element[Device].Value}"></TextBlock>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
    </DataTemplate>

1 个答案:

答案 0 :(得分:0)

解决了它::

链接from StackOverflow。我曾向此提出过类似的问题,两者都有相同的答案。