Ishan070692 Ishan070692 - 4 years ago 199
C# Question

Bind xmldataprovider using MVVM pattern

I have a view model in wpf application, which requires high usage of XML. For this I'm using XMLDataProvider also there are some other properties that are not dependent upon the XML.

So my viewmodel looks like this:

public class ViewModel : ViewModelBase
private XmlDocument _xmlDataProvider;
private string _name;

public string Name
get { return _name; }
_name = value;

public XmlDocument XmlDataProvider
get { return _xmlDataProvider; }
_xmlDataProvider = value;

And my XAML code Looks like this:

<UserControl x:Name="ctrlTemplate" x:Class= "CtrlTemplate"
DataContext="{DynamicResource ViewModel}">
<local:ViewModel x:Key="ViewModel" />

I want to set the xml provider to an internal grid Like this:

<Grid x:Name="grdFill" Margin="0" RenderTransformOrigin="0.502,0.492" HorizontalAlignment="Left">
<XmlDataProvider x:Name="template" Document="{Binding XmlDataProvider}"/> **This is not possible as Document is not a Dependency property**
<Button ="{Binding XPath=Some Xpath}"/>
<Button Content="{Binding Name, Source={StaticResource ViewModel}}"/>

So my question is:

  1. How can I set the Document property of XmlDataProvider, without violating MVVM rules?

  2. I also am using commands in place of events, but The Document property would not be available in the ViewModel.

Answer Source


Here are two tracks to solve your question.

  1. You could make the XmlDataProvider not to be instanciated in XML, but in ViewModel Code.
    So you 'd have a XmlDataProvider property in you ViewModel Code

The DataContext of your UserControl would be the View Model

    <local:ViewModel />

Then your DataBinding on a button could be made with a "more" focused DataContext :

<Button DataContext="{Binding Path=XmlDataProvider}" 
        Content="{Binding XPath=Some Xpath}"/>
  1. Personnaly I would not expose an XmlDocument or XmlDataProvider property from the View Model, but I'd prefer to expose some .Net objects instanciated from Linq to XML


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download