Feeds:
Posts
Comments

Posts Tagged ‘Xml’

Most of us have used ObjectDataProvider to create an object to use as a binding source in Xaml. However, many of you may have never used the XmlDataProvider to do the same. In this post I am going to explain how to use an external XML file to populate a list of ComboBox options. I will then bind a property to the currently selected item of the ComboBox.

The reason I find this so useful is when your application’s end user may need things to frequently change in the future, but has no clue as to how in the present. For example, lets say they have a list of colors that need to be available for their automobile paint. Well next week maroon is the new thing. Do you really want to update your app and re-publish? Wouldn’t you rather give them the ability to just add a new node in an XML file that is sitting on a network drive (or the web) that they have access to? Well now I’m going to show you how.

First we must make an XML file to contain our list of color options. We’ll call the file PaintColors.xml and place it on the root C:\ drive for now (it could be on a network drive, the web, etc.). Here are the contents of the file.


<?xml version="1.0" encoding="utf-8"?>
<PaintColors>
   <Color Name="None"/>
   <Color Name="Red"/>
   <Color Name="White"/>
   <Color Name="Blue"/>
   <Color Name="Maroon"/>
</PaintColors>

Next we must create a new WPF Application. For now we’ll call it XmlDataProviderTest. Once the application is created, we’ll add some code to the MainWindow.xaml.cs file. We need to create a CurrentColor property and give it property change notification by implementing the INotifyPropertyChanged interface. We are going to assign the DataContext as well as the initial CurrentColor value inside the MainWindow constructor. Here is all of the code for the aforementioned.


using System.Windows;
using System.ComponentModel;

namespace XmlDataProviderTest
{
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
            CurrentColor = "Blue";
        }

        public string CurrentColor
        {
            get {  return _currentColor; }
            set
            {
                if (value != _currentColor)
                {
                    _currentColor = value;
                    OnPropertyChanged("CurrentColor");
                }
            }
        }private string _currentColor;

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        void OnPropertyChanged(string propName)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(
                    this, new PropertyChangedEventArgs(propName));
        }

        #endregion

   }
}

Finally we must place a ComboBox and TextBox on our MainWindow.xaml file. This is also where the XmlDataProvider will be declared. In the following code you’ll notice the Source property of the XmlDataProvider points to the location of the PaintColors.xml file on the C:\ drive. As mentioned before, this could point to a network drive, URL, embedded XML file, etc. The XPath property is set here as well. Please note that the XmlDataProvider’s default value for IsAsynchronous is True. This is because when retrieving XML data from RSS feeds or external XML files it is expected to take a while. This is the opposite of an ObjectDataProvider whose default IsAsynchronous value is set to false. The reason for this default is when retrieving data for an ObjectDataProvider we expect retrieval of the source to be very quick. I am setting IsAsynchronous here to false because our XML file is on a network share and contains very little information and thus should be quick to access.

Please note the binding in the ComboBox. The ItemsSource is bound to our PaintColors XmlData. We have chosen to display the Name attribute in the ComboBox and make it the selected value. Finally we are binding our SelectedValue to the CurrentColor string property we previously created in the MainWindow.xaml.cs file. To show everything is working well, I have bound the CurrentColor to a TextBox so we can see it update on the fly.


<Window x:Class="XmlDataProviderTest.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.Resources>
        <XmlDataProvider x:Key="PaintColors" Source="C:\PaintColors.xml" XPath="PaintColors" IsAsynchronous="False" />
    </Window.Resources>

    <StackPanel HorizontalAlignment="Center">
        <ComboBox Grid.Column="4" Grid.Row="2" Width="200" Height="25" Margin="5"
                  ItemsSource="{Binding Source={StaticResource PaintColors}, XPath=./Color}"
                  DisplayMemberPath="@Name"
                  SelectedValuePath="@Name"
                  SelectedValue="{Binding CurrentColor}"/>
        <StackPanel Orientation="Horizontal">
            <Label Content="Current Color:"/>
            <TextBox Text="{Binding CurrentColor, UpdateSourceTrigger=PropertyChanged}" Width="120"/>
        </StackPanel>
    </StackPanel>
</Window>

I hope this provides you all with a clean and simple introduction to XmlDataProviders. For more on synchronous and asynchronous binding have a look at Bea Stollnitz’s blog post here. Enjoy!!

Advertisements

Read Full Post »