ContentControl是最简单的TemplatedControl,而且它在UWP出场频率很高。ContentControl和Panel是VisualTree的基础,可以说几乎所有VisualTree上的UI元素的父节点中总有一个ContentControl或Panel。
因为ContentControl很简单,如果只实现ContentControl最基本功能的话很适合用来做TemplatedControl的入门。这次的内容就是模仿ContentControl实现一个模板化控件MyContentControl,直接继承自Control。
1. 定义属性
/// <summary>/// 获取或设置Content的值/// </summary> public object Content
{ get { return (object)GetValue(ContentProperty); } set { SetValue(ContentProperty, value); }
}/// <summary>/// 标识 Content 依赖属性。/// </summary>public static readonly DependencyProperty ContentProperty =
DependencyProperty.Register("Content", typeof(object), typeof(MyContentControl), new PropertyMetadata(null, OnContentChanged));private static void OnContentChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args){
MyContentControl target = obj as MyContentControl; object oldValue = (object)args.OldValue; object newValue = (object)args.NewValue; if (oldValue != newValue)
target.OnContentChanged(oldValue, newValue);
}protected virtual void OnContentChanged(object oldValue, object newValue){
}/// <summary>/// 获取或设置ContentTemplate的值/// </summary> public DataTemplate ContentTemplate
{ get { return (DataTemplate)GetValue(ContentTemplateProperty); } set { SetValue(ContentTemplateProperty, value); }
}/// <summary>/// 标识 ContentTemplate 依赖属性。/// </summary>public static readonly DependencyProperty ContentTemplateProperty =
DependencyProperty.Register("ContentTemplate", typeof(DataTemplate), typeof(

