Silverlight - Setting DataContext in XAML rather than in constructor?

后端 未结 7 523
心在旅途
心在旅途 2020-12-01 05:42

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 X

相关标签:
7条回答
  • 2020-12-01 05:46

    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.

    0 讨论(0)
  • 2020-12-01 05:54
    <UserControl.Resources>
      <ResourceDictionary>
         <vm:YourModelx:Key="myModel"/>
      </ResourceDictionary>
    </UserControl.Resources>
    <UserControl.DataContext>
       <Binding Source="{StaticResource myModel}"/>
    </UserControl.DataContext>
    
    0 讨论(0)
  • 2020-12-01 05:55

    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>
    
    0 讨论(0)
  • 2020-12-01 06:05

    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>
    
    
    0 讨论(0)
  • 2020-12-01 06:06

    The following monstrosity works in Silverlight 4

    <UserControl 
      DataContext="{Binding HPVM, RelativeSource={RelativeSource Self}}">
    
    0 讨论(0)
  • 2020-12-01 06:10
    <UserControl.DataContext>
      <vm:ThisUCViewModel />
    </UserControl.DataContext>
    
    0 讨论(0)
提交回复
热议问题