views:

6

answers:

1

Hello,

I wish to define the DataContext of my window from 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 ?

+1  A: 

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!

Arcturus
Yes it worked ! So if I understand correctly, when I use the `DataContext = someObject` syntax, the DataContext property automatically instanciates a Binding object for my someObject ?
kbok
No.. it just sets the object directly. When you use a Binding, and a Path to a property, it will register the changes. Using a Binding to an object, not a property of an object is therefor pretty useless; the object will never change, so you will never need to register changes, so you wont need a Binding to a direct object!
Arcturus