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; }
set
{
_name = value;
base.RaisePropertyChangedEvent("Name");
}
}

public XmlDocument XmlDataProvider
{
get { return _xmlDataProvider; }
set
{
_xmlDataProvider = value;
base.RaisePropertyChangedEvent("XmlDataProvider");
}
}
}


And my XAML code Looks like this:

<UserControl x:Name="ctrlTemplate" x:Class= "CtrlTemplate"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WPFControl.UI"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:xckt="clr-namespace:Xceed.Wpf.Toolkit;assembly=Xceed.Wpf.Toolkit"
mc:Ignorable="d"
DataContext="{DynamicResource ViewModel}">
<UserControl.Resources>
<local:ViewModel x:Key="ViewModel" />
</ResourceDictionary>
</UserControl.Resources>


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">
<Grid.DataContext>
<XmlDataProvider x:Name="template" Document="{Binding XmlDataProvider}"/> **This is not possible as Document is not a Dependency property**
</Grid.DataContext>
<StackPanel>
<Button ="{Binding XPath=Some Xpath}"/>
<Button Content="{Binding Name, Source={StaticResource ViewModel}}"/>
</StackPanel>
</Grid>


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

@Ishan,

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

<UserControl.DataContext>
    <local:ViewModel />
</UserControl.DataContext>

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

Regards

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