Many have argued that there are pieces still missing from Windows Runtime XAML that were in WPF. One item that was in WPF was the ability to be notified when a DependencyProperty changed. This functionality is now available in Windows Apps thanks to the new RegisterProperrtyChangedCallback method on DependencyObject. This opens up a world of opportunities for us. This functionality is extremely useful when creating custom controls or wrapping existing controls.
Rather than getting into anything complex, I’ll show a quick sample. A TextBlock control has Text, but no way to be notified when the text changes. We do have the ability to bind to the Text, but we’ll ignore that for now.
We’ll create two TextBlocks and one Button.
<StackPanel>
<TextBlock x:Name="CounterText"/>
<Button Content="Click me" Click="OnButtonClicked"/>
<TextBlock x:Name="DuplicateTextBlock"/>
</StackPanel>
When the button is clicked we’ll set the text for the first TextBlock.
private int _counter;
private void OnButtonClicked(object sender, RoutedEventArgs e)
{
CounterText.Text = string.Format("Clicked {0} times", ++_counter);
}
We’ll also register a callback for when the Text property changes for the CounterText TextBlock. Within the callback we’ll set the text of the other TextBlock.
public MainPage()
{
this.InitializeComponent();
CounterText.RegisterPropertyChangedCallback(TextBlock.TextProperty, OnTextChanged);
}
private void OnTextChanged(DependencyObject sender, DependencyProperty dp)
{
var t = (TextBlock)sender;
DuplicateTextBlock.Text = t.Text;
}
Now every time you click the button, it will set the text of the first TextBlock and the callback will fire setting the text of the second TextBlock!