Thursday, 24 January 2013

WPF MVVM ComboBox Binding to XML Data.

Once again, while browsing StackOverflow.com, I came across a question from a user who needed to fix their ComboBox Binding. The user in question was Binding XML data in Key/Value pairs to the combo box, displaying the Key and wanted to retrieve the Value.

This was achieved using the following example;

My XML Test Data was saved as XMLFile1.xml;

<?xml version="1.0" encoding="utf-8"?>
<Colours>
  <Colour ID="1" Name="None" />
  <Colour ID="2" Name="Red" />
  <Colour ID="3" Name="White" />
</Colours>


My XAML was;






<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="74" Width="150">
    <Window.Resources>
        <XmlDataProvider x:Key="ColourData" Source="/XMLFile1.xml" XPath="Colours" />
    </Window.Resources>
    <Grid>
        <ComboBox x:Name="cmbColour" HorizontalAlignment="Left" Margin="10,10,0,0" 
                  VerticalAlignment="Top" Width="120" DisplayMemberPath="@ID" 
                  ItemsSource="{Binding Source={StaticResource ColourData}, XPath=./Colour}" 
                  SelectedValuePath="@Name"
                  SelectedValue="{Binding SelectedColourValue}"
                  />
    </Grid>
</Window>


And finally my ViewModel was;






Imports System.ComponentModel
Imports System.Xml
 
Class MainWindow : Implements INotifyPropertyChanged
 
    Private _SelectedColourValue As String
    Public Property SelectedColourValue As String
        Get
            Return _SelectedColourValue
 
        End Get
        Set(value As String)
 
            If value.Equals(_SelectedColourValue) = False Then
 
                _SelectedColourValue = value
                RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("SelectedColourValue"))
 
            End If
 
        End Set

End Property


    Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged
 
    Public Sub New()
 
        ' This call is required by the designer.
        InitializeComponent()
 
        ' Add any initialization after the InitializeComponent() call.
        me.DataContext = Me
 
    End Sub
End Class


This successfully displayed the ID property in the ComboBox, and when selected the “SelectedColourValue” Property held the Value.

1 comment:

  1. Getting error in above code. PropertyChanged does not exist so I have used Notify Property changed. Then again got other error : An explicit interface implementation of an event must use event accessor syntax.How to resolve this?

    ReplyDelete