开发者

How is the DataContext typically set?

开发者 https://www.devze.com 2023-01-20 07:53 出处:网络
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.

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 a开发者_C百科ppear 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!


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.


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.

0

精彩评论

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

关注公众号