Does anyone know where I could find a good explanation of dependency properties, or could someone explain them a bit better? I find them very confusing, quite honestly.
I have a UserControl made in XAML in which I nest another user control. When I call this other UserControl within the main one, it looks something like this:
Code:
<local:otherControl />
But I want to pass data to it. In other words, I want to do this:
Code:
<local:otherControl Name="Hello" />
I have heard that in order to do this, I must user DependencyProperty, which just confuses and also angers me.
Let's take this code for example:
Code:
class Node : INotifyPropertyChanged
{
string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
NotifyPropertyChanged("Name");
}
}
/* Events */
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public Node ( )
{
}
}
This looks like perfectly good code to me. If I were to add DependencyProperty stuff, it would look like this:
Code:
class Node : INotifyPropertyChanged
{
string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
NotifyPropertyChanged("Name");
}
}
/* Events */
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
//DependencyProperty stuff
public static readonly DependencyProperty NameProperty =
DependencyProperty.Register("Name", typeof(string), typeof(Node),
new PropertyChangedCallback(NameChangedCallback));
private static void NameChangedCallback(DependencyObject obj,
DependencyPropertyChangedEventArgs args)
{
Node ctl = (Node)obj;
string oldName = (string)args.OldValue;
string newName = (string)args.NewValue;
if ( ctl.Name != null ) ctl.Name = newName;
// Raise the ValueChanged event.
ValueChangedEventArgs e = new ValueChangedEventArgs(newName);
ctl.OnValueChanged(e);
}
public event ValueChangedEventHandler ValueChanged;
protected virtual void OnValueChanged(ValueChangedEventArgs e)
{
ValueChangedEventHandler handler = ValueChanged;
if (handler != null)
{
handler(this, e);
}
}
public Node ( )
{
}
}
Isn't that disgusting? I don't even understand what half of it does because I have found poor documentation relating to DependencyProperty. By adding a DependencyProperty, what more would it do for me? I simply don't understand what they do, or what advantages they offer.