Silverlight - Setting DataContext in XAML rather than in constructor?

MattSlay picture MattSlay · Mar 3, 2009 · Viewed 59.2k times · Source

How can I set the DataContext on my Grid in XAML, instead of in the constructor?

Here is how I do it in the constructor (LayoutRoot is the XAML Grid defined in the XAML):

this.LayoutRoot.DataContext = this.HPVM;

I would prefer to do it right in the XAML, but I do not know how to reference the HPVM object in XAML. HPVM is a public property on the USerControl class.

It works fine as listed above, but again, I just want to know how to properties of the UserControl class in XAML, rather than always having to do it in code.

Here is all the relevant code:

  <UserControl x:Class="SilverlightApplication1.SLHolePattern" x:Name="HolePatternsControl"
    xmlns="http://schemas.microsoft.com/client/2007"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:sys="clr-namespace:System;assembly=mscorlib"    
    xmlns:controls="clr-namespace:Microsoft.Windows.Controls;assembly=Microsoft.Windows.Controls"
    xmlns:local="clr-namespace:SilverlightApplication1"    
    xmlns:GeoPatterns="clr-namespace:GeoPatterns"
    Height="700">


    <UserControl.Resources>
    ...

And here is my constructor where the DataContext is currently set:

namespace SilverlightApplication1
{
    public partial class SLHolePattern : UserControl, INotifyPropertyChanged
    {
        public HolePatternsViewModel HPVM;

        public SLHolePattern()
        {
            InitializeComponent();

            this.HPVM=new HolePatternsViewModel();
            this.LayoutRoot.DataContext = this.HPVM;
            ...more code here
        }

It all works fine, but I just want to learn how to set the DataContext in XAML, not in code.

Answer

Klinger picture Klinger · Mar 4, 2009

The answer Chris gave works just fine. I have tested and it worked for me. You can instantiate your class in XAML (within the UserControl.Resources) and then bind the datacontext to a static resource.

Follow code:


<UserControl ...>
    <UserControl.Resources>
       <myNS:MyClass x:Name="TheContext" x:Key="TheContext"></myNS:MyClass>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="White" DataContext="{StaticResource TheContext}" >
        <TextBlock Text="{Binding Path=Field1}">
        </TextBlock>
    </Grid>
</UserControl>