Click here to Skip to main content
15,445,242 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have created a WPF test application Which contain a xml file and MainWindow.xaml.cs file and a MainWIndow.xaml file and the application contain one comboBox and from the xml values are getting bind . I want to convert the application into MVVM Pattern. Please someone help me on this.

What I have tried:

This is the MainWindow.xaml.cs
public partial class MainWindow : Window
       public MainWindow()
           if (DesignerProperties.GetIsInDesignMode(this))
           XmlDataProvider xdp = this.TryFindResource("XMLDP") as XmlDataProvider;
           if(xdp != null)
               XmlDocument doc = new XmlDocument();
               xdp.Document = doc;

This is the MainWindow.xaml
        <XmlDataProvider Source="Languages.xml" x:Key="XMLDP"/>
        <ComboBox x:Name="cmbName" Height="30" Width="150" ItemsSource="{Binding Source={StaticResource XMLDP},XPath=*/*}"

This is the xml file

<language id="1">

<language id="2">

<language id="3">
Updated 24-May-21 0:40am

1 solution

The XmlDataProvider class is not a DependencyObject, so you cannot bind its Document property to a view-model property.

Instead, you would read the XML file from your view-model, convert it to a list of C# objects, and bind your data to that list.
public class Language
    public Lanuage(XElement element)
        Id = (int)element.Attribute("id");
        Name = (string)element.Element("name");
        CultureCode = (string)element.Element("culture");
    public int Id { get; }
    public string Name { get; }
    public string CultureCode { get; }
public class YourViewModel : ViewModelBase
    public IReadOnlyList<Language> Languages { get; } = LoadLanguages();
    private static IReadOnlyList<Language> LoadLanguages()
        XDocument doc = XDocument.Load("Languages.xml");
        return doc.Root.Elements("language").Select(el => new Language(el)).ToList();
    <ComboBox x:Name="cmbName" ItemsSource="{Binding Path=Languages}" DisplayMemberPath="Name" />
Share this answer
Gita Padhihari 24-May-21 7:37am    
Hi @RichardDeemingWatch Thank you for the solution. I can't find ViewModelBase in my solution . Kindly help me on this.
Richard Deeming 24-May-21 7:47am    
It's whatever base class you're using for your view-models. If you haven't got one already, there are plenty of examples around - eg: A simple ViewModelBase for WPF Apps · GitHub[^]
Gita Padhihari 24-May-21 11:24am    
Thank you
Kenneth Haugland 25-May-21 3:40am    
Can also use BindableBase from Prism if you use that

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900