0

我有一个用户控件,我想将文本框绑定到 XmlDocument。xaml 代码的重要部分如下所示:

...
<UserControl.DataContext>
   <XmlDataProvider x:Name="Data" XPath="employee"/>
</UserControl.DataContext>
...
<TextBox Text={Binding XPath=general/description, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
...

在用户控件的构造函数中,我有以下几行:

string xmlPath = System.IO.Path.Combine(Thread.GetDomain().BaseDirectory, "Data", "TestXml.xml");
FileStream stream = new FileStream(xmlPath, FileMode.Open);
this.Data.Document = new XmlDocument();
this.Data.Document.Load(stream);

如果我更改了文本框文本,则 XmlDocument 数据不会更新。我该怎么做才能实现这一目标?

4

1 回答 1

0

上面的代码对我有用。我没有使用流,而是使用了硬编码数据。

XAML 文件:

    <Window x:Class="TestWPFApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <XmlDataProvider x:Name="Data" XPath="employee"/>
    </Window.DataContext>
    <Grid>
        <StackPanel Orientation="Vertical">
            <TextBox Width="100" Foreground="Red" Height="20" Text="{Binding XPath=general/description, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
            <Button Content="Test" Width="50" Height="20" Click="Button_Click"></Button>
        </StackPanel>
    </Grid>
</Window>

代码背后:

using System.Windows;
using System.Xml;

namespace TestWPFApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.Data.Document = new XmlDocument();
            this.Data.Document.LoadXml(@"<employee><general><description>Test Description</description></general></employee>");
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var data = this.Data.Document.SelectSingleNode("descendant::description").InnerText;
        }
    }
}
于 2013-05-13T13:57:09.217 回答