我试图将一些XML数据绑定到DataGrid,代码工作正常,但我无法绑定到属性值。
<DataGrid Name="productGrid" HorizontalAlignment="Left" Margin="10,66,0,0" VerticalAlignment="Top" Height="459" Width="748" AutoGenerateColumns="false">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding Path=Element[product].Attribute[id].Value}" />
<DataGridTextColumn Header="Kategori" Binding="{Binding Path=Element[category].Value}" />
<DataGridTextColumn Header="Title" Binding="{Binding Path=Element[title].Value}" />
<DataGridTextColumn Header="Beskrivelse" Binding="{Binding Path=Element[description].Value}" />
<DataGridTextColumn Header="Pris" Binding="{Binding Path=Element[price].Value}" />
</DataGrid.Columns>
</DataGrid>
代码背后:
public Page1()
{
InitializeComponent();
var xElem = XElement.Load(AppDomain.CurrentDomain.BaseDirectory + @"\\Data\\Products.xml");
this.defaultView = CollectionViewSource.GetDefaultView(xElem.Elements("product"));
this.defaultView.Filter = w => ((XElement)w).ToString().Contains(freeText.Text);
productGrid.ItemsSource = this.defaultView;
}
private void SearchProducts(object sender, RoutedEventArgs e)
{
// Filter GridView
this.defaultView.Refresh();
}
是否可以将列绑定到属性值?如果是这样,怎么样?
是否有一种更优雅的方式来绑定列,可能来自后面的代码?
答案 0 :(得分:0)
在这种情况下,您可以从绑定中删除一些额外元素,即Element[product]
,这些不是必需的,因为绑定元素是产品本身
例如
<DataGrid Name="productGrid" HorizontalAlignment="Left" Margin="10,66,0,0" VerticalAlignment="Top" Height="459" Width="748" AutoGenerateColumns="false">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding Path=Attribute[id].Value}" />
<DataGridTextColumn Header="Kategori" Binding="{Binding Path=Element[category].Value}" />
<DataGridTextColumn Header="Title" Binding="{Binding Path=Element[title].Value}" />
<DataGridTextColumn Header="Beskrivelse" Binding="{Binding Path=Element[description].Value}" />
<DataGridTextColumn Header="Pris" Binding="{Binding Path=Element[price].Value}" />
</DataGrid.Columns>
</DataGrid>