1

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

任何帮助都会非常有用。

谢谢

詹姆士

4

1 回答 1

0

像这样的东西应该工作:

<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>

您将希望DependencyProperty在您的窗口/控件上为 XmlDataProvider添加一个

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;
于 2012-12-20T20:42:09.590 回答