Silverlight – Setting DataContext in XAML rather than in constructor


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"


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

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

        public SLHolePattern()

            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.

Best Solution

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 ...>
       <myNS:MyClass x:Name="TheContext" x:Key="TheContext"></myNS:MyClass>
    <Grid x:Name="LayoutRoot" Background="White" DataContext="{StaticResource TheContext}" >
        <TextBlock Text="{Binding Path=Field1}">

Related Question