开发者

Defining DataContext from controller code

I wish to define the DataContext of my window f开发者_如何学JAVArom an external class to be able to use DI for my data model. I have read some tutorials about it but I still can't get it to work together. Say we have a simple data model :

class Data 
{
    public String Value { get; set; }

    public Data() 
    {
        Value = "Test";
    }
}

When I instanciate the data object into the XAML code, the data binding operates correctly :

<Window ...>
  <Window.Resources>
    <src:Data x:Key="data" />
  </Window.Resources>
  <Window.DataContext>
    <Binding Source="{StaticResource ResourceKey=data}" />
  </Window.DataContext>
  <Grid>
    <Label Content="{Binding Path=Value}" />
  </Grid>
</Window>

But if I try to bind the data from an external class, the window just shows nothing and I get no error:

<Window ...>
  <Grid>
    <Label Content="{Binding Path=Value}" />
  </Grid>
</Window>

And the main class :

class Test
{
    [@STAThreadAttribute()]
    public static void Main(string[] args)
    {
        MainWindow w = new MainWindow();

        Binding b = new Binding();
        b.Source = new Data();
        w.DataContext = b;

        w.ShowDialog();
    }
}

Am I missing something ? Maybe the DataContext property must be setted from a different thread ?


You can set the Data directly in your code behind:

class Test
{
    [@STAThreadAttribute()]
    public static void Main(string[] args)
    {
        MainWindow w = new MainWindow();

        w.DataContext = new Data();

        w.ShowDialog();
    }
}

Or use the Binding, and you should set the Binding differently in code behind:

class Test
{
    [@STAThreadAttribute()]
    public static void Main(string[] args)
    {
        MainWindow w = new MainWindow();

        Binding b = new Binding();
        b.Source = new Data();
        SetBinding(DataContextProperty, b);

        w.ShowDialog();
    }
}

in your example you set the Binding as DataContext, meaning you will bind not to the Data, but to the Binding object itself. If you use Xaml, it will intenally determine if you use a binding, and use the latter instead of the first!

Hope this helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜