Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...