在WPF中使用c#绑定xml
本文关键字:绑定 xml WPF | 更新日期: 2023-09-27 17:49:18
我有以下xml
<?xml version="1.0" encoding="utf-8"?>
<Categories>
<Product>
<Product_id>dave</Product_id>
<Product_name>smith</Product_name>
<Product_price>none</Product_price>
</Product>
</Categories>
我想通过代码绑定它,因为我一直在与WPF和XAML作斗争。除非有人能告诉我一个简单的方法。
以下c#
XmlDataProvider xds= new XmlDataProvider();
xds.Source = new Uri(@"C:'Users'Roi'Desktop'dave'Sum.xml", UriKind.RelativeOrAbsolute);
xds.XPath = "/Categories/Product/@Product_id";
Binding binding = new Binding();
binding.Source = xds;
BindingOperations.SetBinding(listView1, ItemsControl.ItemsSourceProperty, binding);
任何帮助都是非常感谢的。
谢谢詹姆斯
应该这样做:
<Window x:Class="WpfApplication4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication4"
Title="MainWindow" Height="300" Width="400" Name="UI" >
<Grid>
<ListView DataContext="{Binding MyXmlDataSource}" ItemsSource="{Binding XPath=/Product/@Product_id}" />
</Grid>
</Window>
您将希望在您的窗口/控件上为XmlDataProvider添加DependencyProperty
public XmlDataProvider MyXmlDataSource
{
get { return (XmlDataProvider)GetValue(MyXmlDataSourceProperty); }
set { SetValue(MyXmlDataSourceProperty, value); }
}
// Using a DependencyProperty as the backing store for MyXmlDataSource. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyXmlDataSourceProperty =
DependencyProperty.Register("MyXmlDataSource", typeof(XmlDataProvider), typeof(MainWindow), new UIPropertyMetadata(null));
然后你可以分配XmlDataProvider
XmlDataProvider xds= new XmlDataProvider();
xds.Source = new Uri(@"C:'Users'Roi'Desktop'dave'Sum.xml", UriKind.RelativeOrAbsolute);
xds.XPath = "/Categories";
MyXmlDataSource = xds;