Silverlight - Setting DataContext in XAML rather than in constructor?

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>


The following monstrosity works in Silverlight 4

<UserControl 
  DataContext="{Binding HPVM, RelativeSource={RelativeSource Self}}">

<UserControl.DataContext>
  <vm:ThisUCViewModel />
</UserControl.DataContext>

try something like this.....

<Grid DataContext="{Binding Path=HPVM}">
</Grid>

where HPVM is a public member of this--> your form etc.

Create the instance of your class in the xaml, by adding something like this to your resources section.... (don't forget to add your xmlns namespace)

<my:bogart x:Key="franken"/>

then, bind the data context to the static resource you just added....

<Grid x:Name="LayoutRoot" Background="White" DataContext="{StaticResource franken}">
    <TextBox  Background="Red" Foreground="White" Text="{Binding Path=sum}"  />
</Grid>

In Silverlight 4, I was able to get this working by doing the following:

Give the Page/UserControl an x:Name="myPage"

In your control binding use normal Element bidning syntax. In my case I want to bind to an observable collection of objects in my code behind for my ItemsSource property:

<ComboBox 
    ItemsSource={Binding ElementName=myPage, Path=MyObservableObjectList, Mode=TwoWay}

I haven't tried this with DataContext but know you can do element to element binding for DataContext as I do this for Grids whose context is based on the selected item of some other drop down on the page.