WPF databinding simplyfies many complex operations and allows to achieve the result by only using the XAML code. In this article we will demonstrate how to use a custom dependency property in a databinding operation inside a user control.
Introduction:
WPF databinding simplyfies many complex operations and allows to achieve the result by only using the XAML code. In this article we will demonstrate how to use a custom dependency property in a databinding operation inside a user control.
Simple DataBinding:
Let's say we want to display the SelectedItem text from the ComboxBox in a Label control. Here is the code which is not using the databinding powers of WPF.
And here is the cbItems_SelectionChanged event.
Now, if you select an item from the ComboBox the Label will display the Text of the SelectedItem.
The above code will work correctly but this can easily be achieved using WPF databinding operation. Check out the code below which is used to solve this using WPF.
As, you can see that we only used the XAML code to acheive the desired result.
Creating FileInputBox User Control:
The example discussed in this article came from WPF Unleashed by Adam Nathan. We will create a user control FileInputBox. The purpose of the control is to display the selected file into the TextBox. The file will be selected from the client's machine by using the OpenFileDialog control.
Here is the XAML code for the FileInputBox control which creates a Button and TextBox.
The BtnSelectFile_Click is responsible for popping up the OpenFileDialog. The implementation is shown below:
The FileName is a string property which returns the value in the DependencyProperty. Let's see the implementation of the DependencyProperty.
Now, let's add the databinding expression to the XAML code to use the FileName property.
The name of the user control is "root".
Finally, let's add the control to the Window.
When you run the above code you will see the user control inside your window. Select a file using the browse button and see the name of the file appear in the TextBox control. Wait! it does not appear in the TextBox control. This is a gotcha in WPF when using databinding with custom dependency properties. The workaround is to create a callback method which will be called when the dependency property is changed.
Here is the modified code for the dependency property:
Now, if you run the above code it will work as expected.
Conclusion:
In this article we learned how to create a custom dependency property and use it with our own user control. We also learned about a small tip when using databinding with custom dependency properties.
References:
1) WPF Unleashed by Adam Nathan
2) WPF Custom Control Dependency Property Gotcha
[Download Sample]