Silverlight - Setting DataContext in XAML rather than in constructor?

白昼怎懂夜的黑 提交于 2019-11-27 07:14:49

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>
Doug

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.

Srdjan Jovcic

This is not possible (It is possible in WPF with {Binding RelativeSource={RelativeSource Self}}, but Silverlight is more limited.

You have to do it through code.

<UserControl.Resources>
  <ResourceDictionary>
     <vm:YourModelx:Key="myModel"/>
  </ResourceDictionary>
</UserControl.Resources>
<UserControl.DataContext>
   <Binding Source="{StaticResource myModel}"/>
</UserControl.DataContext>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!