I'm building a simple UserControl example with DependencyProperties so that the properties of the control can be changed in XAML (code below).
But of course in my application I don't want this control to have tightly-coupled code-behind, but instead the user control will be a view called "DataTypeWholeNumberView" and it will have its own ViewModel called "DataTypeWholeNumberViewModel".
So I am going to implement the DependencyProperty logic below into the ViewModel, but in ViewModels I usually inherit INotifyPropertyChanged which seems to give me the same functionality.
So what is the relationship between:
XAML:
<UserControl x:Class="TestDependencyProperty827.SmartForm.DataTypeWholeNumber"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel>
<StackPanel HorizontalAlignment="Left" VerticalAlignment="Top" Orientation="Horizontal">
<TextBlock Text="{Binding Label}"/>
</StackPanel>
</StackPanel>
</UserControl>
Code Behind:
using System.Windows;
using System.Windows.Controls;
namespace TestDependencyProperty827.SmartForm
{
public partial class DataTypeWholeNumber : UserControl
{
public DataTypeWholeNumber()
{
InitializeComponent();
DataContext = this;
}
public string Label
{
get
{
return (string)GetValue(LabelProperty);
}
set
{
SetValue(LabelProperty, value);
}
}
public static readonly DependencyProperty LabelProperty =
DependencyProperty.Register("Label", typeof(string), typeof(DataTypeWholeNumber),
new FrameworkPropertyMetadata());
}
}
INotifyPropertyChanged is an interface that exists in .Net since 2.0. It basically allows objects to notify when a property has changed. An interested party can perform certain actions when this event is raised. The problem with it is that it only publishes the name of the property. So you end up using reflection or some iffy if statements to figure out what to do in the handler.
DependencyProperties are a more elaborate construct that supports default values, change notifications in a more memory-efficient and performant way.
The only relationship is that the WPF binding model supports binding to either DependencyProperties or to standard Clr properties, with an INotifyPropertyChanged implementation. Your ViewModel could be a DependecyObject as well and the third option would be to bind to the ViewModel's DependencyProperties!
Kent Boogaart wrote a very interesting article on having a ViewModel be a POCO vs a DependencyObject.
I don't really think there is a relationship between DependencyProperties and INotifyPropertyChanged. The only magic here is that the Binding classes/utils are smart enough to recognize a DependencyProperty and bind directly to it, or subscribe to the binding-target's notify-property-changed event and wait for that to fire.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With