Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"     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.

like image 631
MattSlay Avatar asked Mar 03 '09 15:03

MattSlay


1 Answers

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>  
like image 195
Klinger Avatar answered Sep 20 '22 03:09

Klinger