What is a DataContext in C#? Are DataContext a kind of new version of DataSource?
What is a DataContext in C#? Are DataContext a kind of new version of
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
(It sounds you mean the
FrameworkElement.DataContextproperty 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:
then you just set its DataContext to that object. Then the XAML for displaying information from that Employee object could be as simple as:
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.