[Translate] register any dependency attribute changes in Windows 10 applications.
Address: http://visuallylocated.com/post/2015/04/01/Registering-to-any-DependencyProperty-changing-in-Windows-Apps.aspx
There are still many proofs that many features in WPF are missing in the Windows Runtime XAML. One of them is in WPF. You can get a notification (Link) when the Dependency Property Changes ). Now, thanks to the DependencyObject class's RegisterPropertyChangedCallback method (Link), this function can be implemented in Windows applications. This will open a new world of opportunities for us. This feature is useful when we create custom controls or wrap existing controls.
Instead of going into something complicated, I prefer to use a quick example. A text box with text, but cannot be notified when the text changes. Of course, we can also use data binding to bind to the Text attribute, but ignore it now.
Now, we create two text boxes and one button.
<StackPanel> <TextBlock x:Name="CounterText"/> <Button Content="Click me" Click="OnButtonClicked"/> <TextBlock x:Name="DuplicateTextBlock"/></StackPanel>
When this button is clicked, we will set the text in the first text box.
private int _counter; private void OnButtonClicked(object sender, RoutedEventArgs e){ CounterText.Text = string.Format("Clicked {0} times", ++_counter);}
At the same time, we also register a callback function for the CounterText Text box that changes the Text attribute. In the callback function, we will set the text of another text box.
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 a button, you will set the text in the first text box, And the callback function will trigger and set the text in the second text box!