Wpf 使用DataGridTemplateColumn将Datagrid数据绑定到XML
我有这样一个XML::Wpf 使用DataGridTemplateColumn将Datagrid数据绑定到XML,wpf,datagrid,combobox,datatemplate,xml-binding,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> </Devic
<?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>
我的代码如下所示:
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在组合框中以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>
解决了这个问题:
链接。我问了一个类似的问题,两个问题的答案都是一样的
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 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>