Click here to Skip to main content
15,867,594 members
Articles / Desktop Programming / XAML
Tip/Trick

WPF Binding Window/UserControl to Self

Rate me:
Please Sign up or sign in to vote.
4.50/5 (6 votes)
9 Apr 2018CPOL2 min read 31K   423   8   1
Shows how to set DataContext of View to itself using XAML and discusses the advantages of INotifyPropertyChanged to DependencyProperty

Introduction

I recently started a project where in order to bind to properties within the Code section of UserControl (or Window), they were using DependencyProperty definitions, in fact sometimes it was even worse, they were also deriving from INotifyPropertyChanged, and using the OnPropertyChanged.

Many people consider code within the Code section of a XAML document bad, and that only in rare instances will I put code into the Code section, preferring to create a behavior, which can be reused.

There are times when it is necessary to use DependencyProperty definitions, but seldom in a UserControl.

Difference between DependencyProperty and INotifyPropertyChanged

The following was published by "LBugnion":

INotifyPropertyChanged has advantages over DependencyProperty definitions:

  • This is more lightweight
  • Allows you more freedom in modeling your objects
  • Can be serialized easily
  • You can raise the event when you want, which can be useful in certain scenarios, for example when you want to bundle multiple changes in only one UI operation, or when you need to raise the event even if the data didn't change (to force redraw...)

A DependencyProperty has the following advantages:

  • Callback mechanism (almost) for free, allowing notification when the property value changes
  • Coercion mechanism allows you to define rules for max, min and present value of the property
  • It is faster: Optimizing Performance: Data Binding

There are apparently other considerations. The consensus is that DependencyProperty definitions are great for controls (and you can implement a CustomControl), but for data objects, you should implement INotifyPropertyChanged.

Doing the Binding to the Window/UserControl

I saw the following when looking at the code in the project:

C#
public UserInputControl()
{
    InitializeComponent();
    LayoutRoot.DataContext = this;
}

Although this is fine, I really prefer to do this in XAML.

You can actually do the setting of the DataContext in XAML, if there is a separate class that is associated with DataContext for a XAML file, I will do the following:

XML
<Window.DataContext>
    <local:ViewModel/>
</Window.DataContext>

Normally, I will use this method of associating a ViewModel with a View only for sample projects. The nice thing about this technique is that it creates an instance of the ViewModel and automatically assigns it to the DataContext of the View.

Maybe you think you could use this method for associating the DataContext with the class itself. NO!!! When you try to use the XAML above for the class itself, a new instance of the XAML and class is created, and that creates a new instance of the XAML and class again. This happens recursively so you run out of memory.

The following XAML is one way to associate the DataContext with the class itself:

XML
<Window x:Class="DataContextToSelfSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:local="clr-namespace:DataContextToSelfSample"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        DataContext="{Binding RelativeSource={RelativeSource Self}}"
        Title="MainWindow"
        Width="400"
        Height="300"
        mc:Ignorable="d">

What is happening is that the RelativeSource of the Binding is being used with the RelativeSource as Self.

History

  • 04/09/2018: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Clifford Nelson Consulting
United States United States
Has been working as a C# developer on contract for the last several years, including 3 years at Microsoft. Previously worked with Visual Basic and Microsoft Access VBA, and have developed code for Word, Excel and Outlook. Started working with WPF in 2007 when part of the Microsoft WPF team. For the last eight years has been working primarily as a senior WPF/C# and Silverlight/C# developer. Currently working as WPF developer with BioNano Genomics in San Diego, CA redesigning their UI for their camera system. he can be reached at qck1@hotmail.com.

Comments and Discussions

 
PraiseNice Pin
Router Customer Support 9-Apr-18 18:58
professionalRouter Customer Support 9-Apr-18 18:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.