官术网_书友最值得收藏!

Catching changing Dependency Property values

As we saw at the beginning of this chapter, the WPF Framework won't call the CLR property wrappers of our Dependency Properties when the property values are changing. However, there is a way to accomplish this using callback handlers. In fact, we've already seen an example of this when we were looking at the creation of the OnEnterKeyDown Attached Property. Let's remind ourselves what that looked like:

public static DependencyProperty OnEnterKeyDownProperty =  
  DependencyProperty.RegisterAttached("OnEnterKeyDown", 
typeof(ICommand), typeof(TextBoxProperties),
new PropertyMetadata(OnOnEnterKeyDownChanged));

...
public static void OnOnEnterKeyDownChanged(
DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e) { TextBox textBox = (TextBox)dependencyObject; if (e.OldValue == null && e.NewValue != null) textBox.PreviewKeyDown += TextBox_OnEnterKeyDown; else if (e.OldValue != null && e.NewValue == null) textBox.PreviewKeyDown -= TextBox_OnEnterKeyDown; }

For this Attached Property, we used a particular overload of the DependencyProperty.RegisterAttached method that accepts a PropertyMetadata object, which enabled us to assign a PropertyChangedCallback handler to the property. Note that there is an identical overload for the DependencyProperty.Register method for declaring Dependency Properties.

Program execution will enter these PropertyChangedCallback handlers each time their related Dependency Property changes, so that makes them perfect for debugging their values. While we don't often need to attach these handlers, it only takes a moment to add one when we need to and they enable us to find out what's going on with the Dependency Property values at runtime.

主站蜘蛛池模板: 民勤县| 泾源县| 蓝山县| 杭锦后旗| 寿阳县| 营口市| 彩票| 汶川县| 横峰县| 郎溪县| 马边| 布拖县| 富锦市| 喀喇| 康马县| 进贤县| 台湾省| 兴城市| 永川市| 襄汾县| 清新县| 长寿区| 正定县| 平果县| 曲沃县| 滨海县| 绵阳市| 靖州| 马尔康县| 乌恰县| 富蕴县| 鄂托克前旗| 巩留县| 五家渠市| 伊吾县| 宣汉县| 会宁县| 洛南县| 错那县| 深圳市| 县级市|