Bastien Vandamme
Bastien Vandamme

Reputation: 18465

Are DataContext a kind of new version of DataSource?

What is a DataContext in C#? Are DataContext a kind of new version of DataSource?

Upvotes: 1

Views: 2430

Answers (2)

Sean U
Sean U

Reputation: 6850

(It sounds you mean the FrameworkElement.DataContext property that appears in WPF. If not, oops.)

It's somewhat similar to DataSource, but is much more flexible. In WPF, a DataContext can be literally any object that has properties. To bind to a property, you just specify its name and WPF takes care of the rest for you by fishing the specified property out of the DataContext with some reflection magic. (Fields are not supported.)

For example, if you're binding a view (say, a UserControl or Window) to an Employee object:

class Employee {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    // more stuff. . .
}

then you just set its DataContext to that object. Then the XAML for displaying information from that Employee object could be as simple as:

<Label Content="{Binding FirstName}"/>
<Label Content="{Binding LastName}"/>

Optionally, the DataContext can provide additional functionality that allows for richer binding. For example:

  • If it implements INotifyPropertyChanged or has dependency properties, changes to the DataContext will be automatically reflected in the UI.

  • Properties that have setters support two-way binding.

  • If it implements INotifyDataErrorInfo then you can do form validation.

  • If it's an ADO.NET object, you get all the usual ADO.NET binding magic.

Upvotes: 3

Justin Niessner
Justin Niessner

Reputation: 245429

A DataContext represents the database in either LINQ to SQL or Entity Framework.

It's not quite an analog to anything else in .NET as it handles a lot of different things (change tracking, sql generation, etc).

Upvotes: 1

Related Questions