Some days ago I started to think about my WPF project I have to code in order to complete my university WPF course. I have worked with C# for quite a while, but the Binding paradigm was something I had never used in its full potential. When you first face Bindings it may come natural to write something like that:
public string Source { get; set; }
<TextBlock Name="txt" Text="{Binding Path=Source}" />
Unfortunately that won’t work. First, you have to bind the Text Property to a DependencyProperty and second you have to use that DependencyProperty in your Source property. That way the binding “will know” when the value has changed.
Let’s first create our DependencyProperty(Window1 is the class used for the example):
public static readonly DependencyProperty DpSource =
DependencyProperty.Register("Source",
typeof(string), typeof(Window1),
new PropertyMetadata(Window1.ValueChanged));
PropertyMetadata defines certain behavior aspects of a dependency property as it is applied to a specific type, including conditions it was registered with. Here is and the ValueChanged static method:
private static void ValueChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
Window1 win = (Window1)o;
win.txt.Text = (string)e.NewValue;
}
At the end we have to modify our string property to use the DependencyProperty
public string Source
{
get { return (string)GetValue(DpSource); }
set { SetValue(DpSource, value); }
}
Now we can use
<TextBlock Name="txt" Text="{Binding Path=Source}" />
If you want to test it, just add a button with a handler for the click event:
private void btn_Click(object sender, RoutedEventArgs e)
{
Source = DateTime.Now.ToString();
}
Here is the simple demo I used for the examples.
DependencyProperty.zip (44.40 kb)