tags:

views:

24

answers:

2

I've created a new WPF project, and threw in a DataGrid. Now I'm trying to figure out the easiest way to bind a collection of data to it.

The example I downloaded seems to do it in the window c'tor:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel();
    }
}

But then the bindings don't seem to appear in the Visual Studio's Properties window. I'm pretty sure there's a way to set the data context in XAML too... it would make me even happier if I could do it directly through the properties window, but all the Binding options are empty. What's the typical approach?

Edit: At 14 minutes, he starts to talk about other methods of setting the data context, such as static resources, and some "injection" method. I want to learn more about those!

+1  A: 

Have a look at the MVVM design pattern. This pattern is very suitable for wpf applications.

There is described where to store your data and how to bind your ui to the data.

PVitt
Was hoping for a quick answer, not another monster tutorial ;) I've read about MVVM wrt ASP .NET MVC, but I specifically want to know how to bind the data such that it works with the properties window.
Mark
+2  A: 

What I typically do is use MVVM. You can implement a simplified version by setting the data context in your code behind and having a model type class that holds your data.

Example: In your code behind

DataContext = Model; // where Model is an instance of your model

then in your view

<DataGrid .... ItemsSource="{Binding SomeProperty}">....

Where SomeProperty is an enumerable property on your view model

You can also set a data context in XAML by using the DataContext property

<uc:SomeUserControl DataContext="{Binding AnotherProperty}"....

This will run your user control within the DataContext of the AnotherProperty on your model.

Note that this is grosely simplified but it'll get you on your way.

Darko Z