ContentControl是最簡(jiǎn)單的TemplatedControl,而且它在UWP出場(chǎng)頻率很高。ContentControl和Panel是VisualTree的基礎(chǔ),可以說(shuō)幾乎所有VisualTree上的UI元素的父節(jié)點(diǎn)中總有一個(gè)ContentControl或Panel。
因?yàn)镃ontentControl很簡(jiǎn)單,如果只實(shí)現(xiàn)ContentControl最基本功能的話很適合用來(lái)做TemplatedControl的入門。這次的內(nèi)容就是模仿ContentControl實(shí)現(xiàn)一個(gè)模板化控件MyContentControl,直接繼承自Control。
1. 定義屬性
/// <summary>/// 獲取或設(shè)置Content的值/// </summary> public object Content { get { return (object)GetValue(ContentProperty); } set { SetValue(ContentProperty, value); } }/// <summary>/// 標(biāo)識(shí) 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>/// 獲取或設(shè)置ContentTemplate的值/// </summary> public DataTemplate ContentTemplate { get { return (DataTemplate)GetValue(ContentTemplateProperty); } set { SetValue(ContentTemplateProperty, value); } }/// <summary>/// 標(biāo)識(shí) ContentTemplate 依賴屬性。/// </summary>public static readonly DependencyProperty ContentTemplateProperty = DependencyProperty.Register("ContentTemplate", typeof(DataTemplate), typeof(