我有一个UserControl,我想将文本框绑定到XmlDocument。 xaml代码的重要部分如下:
...
<UserControl.DataContext>
<XmlDataProvider x:Name="Data" XPath="employee"/>
</UserControl.DataContext>
...
<TextBox Text={Binding XPath=general/description, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
...
在usercontrol的构造函数中,我有以下几行:
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数据。为了达到这个目的,我该怎么做?
答案 0 :(得分: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;
}
}
}