KusziWorks
KusziWorks

Reputation: 65

using xml in wpf mvvm

I have a model

private XmlDataProvider _xmlProvider;
public XmlDataProvider XmlProvider
{
        get { return _xmlProvider; }
        set { _xmlProvider = value; OnPropertyChanged("XmlProvider"); }
}

in the model constructor i read an xml file

var doc = new System.Xml.XmlDocument();
doc.Load("books.xml");

 XmlProvider = new XmlDataProvider()
 {
   Document = doc,
   XPath = @"/root"
 };

the xml file only has a root and 1 Element

<proba author="probaauthor"/>

in the viewmodel i have a reference to model

private Model _model;
public Model Model
{
        get { return _model; }
        set
        {
            _model = value;
            OnPropertyChanged("Model");
        }
}

in the view:

xmlns:localMvvmxml="clr-namespace:MvvmSamples.Mvvm.SimpleXml"

<Grid.Resources>
        <localMvvmxml:ViewModel x:Key="MyXmlProvider"/>

and below I have a stackpanel with a textbox

<StackPanel Orientation="Horizontal" DataContext="{StaticResource MyXmlProvider}" Margin="5">
            <TextBox  Text="{Binding XPath=/root/proba/@author}" Width="113"></TextBox>

of course its not working, because i could not reach the provider. So What to write in the TextBox Binding?

thx. charlie

Upvotes: 1

Views: 2949

Answers (1)

djangojazz
djangojazz

Reputation: 13242

I am guessing your View is not bound to your Viewmodel possibly. I am guessing when you are performing the {Binding XPath=(location)} It is not knowing that your view is using a Viewmodel for it's binding.

This may help a little bit keeping in mind the namespace declarations for your code may be different.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
                    xmlns:vm="clr-namespace:MvvmSamples.Mvvm.ViewModels" 
                    xmlns:vw="clr-namespace:MvvmSamples.Mvvm.View">

<DataTemplate DataType="{x:Type vm:SimpleXMLViewModel}">
        <vw:SimpleXML />
    </DataTemplate>

Also keep in mind a good example here for MVVM: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

Upvotes: 1

Related Questions