Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to update xmlDataProvider when xml document changes at runtime in WPF?

    • 0
    • 1
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 439
    Comment on it

    Some time we need a situation where we bind WPF controls with XmlDataProvider and XML is changes dynamically at run time. Then we need to change the data in WPF controls automatically.
    for eg: we bind list of items with XmlDataProvider and user has the facility the change the item name at runtime. So if user change the item name then updated name should be automatically display  in UI without reload.

    In XAML file:

    XmlDataProvider:

    <XmlDataProvider x:Key="XmlDataProvider1" Source="XmlFiles/XmlFile1.xml" XPath="/TestGroups" />

    ItemControl to display list:

    <ItemsControl x:Name="ItemControl1"  ItemsSource="{Binding Source={StaticResource XmlDataProvider1},XPath=TestGroup}"/>  

    TextBlock that contain selected list item:

    <TextBlock Text="{Binding XPath=Name}"   VerticalAlignment="Center"  />

    Suppose we update the list item when user changes the content of another textbox

    In code behind:

    private void TextBox1_LostFocus(object sender, RoutedEventArgs e)
       {
    	string filepath = "..\\..\\XmlFiles\\XmlFile1.xml";
    	XmlDocument doc = new XmlDocument();
    	doc.Load(filepath);
    	//do changes in xml document according to your condition
    	doc.Save(filepath);
        //Find XmlDataProvider
    	XmlDataProvider xmlProvider = ItemControl1.FindResource("XmlDataProvider1") as XmlDataProvider;
    	if (xmlProvider != null && xmlProvider.Document != null)
    	{
    		xmlProvider.Document = doc;  //assign XmlDataProvider to updated xml document
    		xmlProvider.Refresh();       // Refresh XmlDataProvider
    	}
    }

    Hope this code will help you. Thanks

 1 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: