Creating Binding for a Property – from Code

Dependency properties are making easy to attach a user interface to a specific property of the code from XAML. However, attaching the user interface to the same property is not possible only from the XAML. We can do the same from the code too. The completed solution for this article can be found in the Z10_BindingFromCode directory of my WpfWednesday git repository.

Let’s suppose that we have the following MainWindow defined in XAML:

What we would like to accomplish is that by pressing the button, we replace the text “Old Label Value” on the text block with “New Label Value”.

The first thing that we will need to be able to achieve this is that we need access to the button and the text block from the code behind file of the MainWindow. This can be done by adding “x:Name” property to the definition of the controls. Here, I am naming the button as UpdateLabelButton and the label as UpdatedLabel.

We add a property to the MainWindow so that the label can be bound to this property. This will have the default value of “Old Label Value”.

So, let’s bind the Text property of the TextBlock to this property. In the constructor of MainWindow these two lines are going to accomplish it:

The first line defines the binding. nameof(LabelData) will generate the string “LabelData” and this should be the same as the name of the property defined previously. The properties for the binding are:

  • The Source, which is set to this. This is going to select the object from which we are going to obtain the data for the property.
  • The Mode, which is set to OneWay. This will result in the binding only updated when the value on the MainWindow object changes.

The next line, sets up the binding’s target. This is achieved by calling BindingOperations.SetBinding with the following parameters:

  • UpdatedLabel, this is the TextBlock that we are going to update.
  • TextBlock.TextProperty, this is the dependency property which should be updated with the value of the binding.
  • Binding, this is the binding that we defined in the previous line.

Now let’s test it. By inserting the next line into the MainWindow constructor running and pressing the button we are going to change the value of the LabelData property on the MainWindow and as a result the Text property of the TextBlock is also going to be updated.

You can connect with me on LinkedIn, Twitter or you can register on the blog. Share if you found this article useful or know somebody who would benefit from reading it.

By subscribing to the email list, you will be notified about new posts.
Loading

No comments yet.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Powered by WordPress. Designed by WooThemes