Reputation: 110
I recognize that this question is similar to others, but the others have not worked in my situation. I am trying to Two-Way Bind a textbox in my WPF to an XML file.
The data comes in perfectly into the textbox, but when I edit the textbox, the XML file is never changed. Based on what I have found online, my code seems like it should work. Here it is:
MainWindow.xaml
<Window x:Class="Learning_0._002.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Main Window"
WindowStartupLocation="CenterScreen"
Height="400" Width="950">
<Grid>
<Grid.Resources>
<XmlDataProvider x:Key="BusinessInfo" Source="BusinessData.xml" XPath="/Businesses/Business"/>
</Grid.Resources>
<Grid x:Name="BusinessInfo" DataContext="{StaticResource BusinessInfo}">
<TextBox Name="Name" Grid.Row="0" Grid.Column="1" Text="{Binding XPath=@Name,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Margin="106,93,717,250"/>
</Grid>
</Grid>
BusinessData.xml
<?xml version="1.0" encoding="utf-8" ?>
<Businesses>
<Business Name="Sample Company" Address="1234 East Road St. City, California 90068" Phone="555-555-5555" Fax="555-555-5556" Email="[email protected]" Website="www.example.com"/>
</Businesses>
I am new to this, and cannot find my error. Any corrections are appreciated!
Upvotes: 1
Views: 1032
Reputation: 48
Here's a question that is very similar to yours - WPF two-way binding XML
It looks like what you need to do is instead of using a Grid.Resources you need use a datacontext instead. If you're going to be doing more advanced work I would recommend you use a class that contains all the data behind your UI elements. View this MSDN for more information - http://msdn.microsoft.com/en-us/library/ms743695(v=vs.110).aspx
<Grid.DataContext>
<XmlDataProvider x:Name="XMLData" Source="BusinessData.xml" XPath="/Businesses/Business"/>
</Grid.DataContext>
<Grid x:Name="BusinessInfo" Margin="98,49,118,144">
<TextBox Name="Name" Text="{Binding XPath=@Name, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" TextChanged="Name_TextChanged" />
</Grid>
And then in C# you will save it whenever they enter text into the textbox
private void Name_TextChanged(object sender, TextChangedEventArgs e)
{
XMLData.Document.Save("XMLFile1.xml");
}
You should know that when you save the file it will save to the same directory as where you run your executable. You can of course change where you save it to be the actual source of the XML.
Upvotes: 1