2013-05-13 58 views
0

我有一個UserControl,我想將文本框綁定到一個XmlDocument。 的XAML代碼的重要組成部分看起來像:Databinding XmlDocument

... 
<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的數據不更新。我需要做些什麼來實現這一目標?

回答

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