繁体   English   中英

在WPF中使用C#绑定xml

[英]binding xml using C# in WPF

我有以下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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM