很早之前就看到DependencyProperty,但是每次看到都不想去深入,一眼看過去好難的樣子,今天靜下來學習一下,怕自己過幾天又忘了,來記錄一下自己學習的東西。
首先我們來看看這個東西,
public static readonly DependencyProperty ItemContainerStyleProperty = DependencyProperty.Register("ItemContainerStyle", typeof(string), typeof(MyControl), new PropertyMetadata(null, OnItemContainerStylePropertyChanged));
第一眼被嚇懵了,都干嘛的,好厲害的樣子,下面慢慢來說:上面就是定義了一個依賴屬性,干嘛用的,看名字就是用來設置屬性的,來看看參數ItemContainerStyle這個相當於標示符,在你寫xaml設置的時候,系統會去找到你設置的這個名字進行操作,typeof(string)設置類型,typeof(MyControl)這個告訴系統你這個注冊的屬性是屬於哪個類的,new PropertyMetadata(null, OnItemContainerStylePropertyChanged)屬性值改變時觸發的事件和屬性的初始值
public string ContentInfo { get { return (string)GetValue(ItemContainerStyleProperty); } set { SetValue(ItemContainerStyleProperty, value); } }
上面這個應該沒問題了,就是設置或者獲取屬性了,ContentInfo就是你調用自己寫的控件時可以看到的屬性了
[TemplatePart(Name = InnerSelectorName, Type = typeof(LongListSelector))] [StyleTypedProperty(Property = "MyWidth", StyleTargetType = typeof(MyControl))] [TemplateVisualState(Name =”Selected“, GroupName = "SelectionStates")]
剛看到上面這幾個大括號我又懵了,慢慢來吧:
TemplatePart的作用是*.cs中對於*.xaml中定義的控件進行獲取,並進行操作,不好理解,其實就是在資源字典ResourceDictionary中(也就是一個.xaml)定義中可以使用.cs的屬性一些東西,.cs可以使用到.xaml里面的動畫一些東西
StyleTypedProperty: FontSize="{TemplateBinding FontSize}“這個大家應該在自定義控件時在.xmal經常看到吧,改一下FontSize="{TemplateBinding MyWidth}“,沒錯StyleTypedProperty就是關聯cs里面的MyWidth屬性
TemplateVisualState:這個就是我們經常看到的過度狀態了,看看這個代碼,是不是明白了
<VisualStateGroup x:Name="SelectionStates"> <VisualState x:Name="Selected"/> </VisualStateGroup>
說到底上面的這幾個都是*.cs中對於*.xaml中定義的控件進行獲取,並進行操作,xaml里面可以用cs里面設置的屬性,cs里面可以調用.xmal里面寫的個種動畫效果
然后來說說EventHandler事件,來代碼
public event EventHandler ManipulationStateChanged; public event PropertyChangedEventHandler PropertyChanged; public override void OnApplyTemplate() { base.OnApplyTemplate(); _myControl.Clear(); if (_myControl!= null) { _myControl.ManipulationStateChanged -= OnInnerSelectorManipulationStateChanged; _innerSelector.PropertyChanged -= OnInnerSelectorPropertyChanged; } _myControl= this.GetTemplateChild(InnerSelectorName) as LongListSelector; if (_myControl!= null) { _myControl.ManipulationStateChanged += OnInnerSelectorManipulationStateChanged; _myControl.PropertyChanged += OnInnerSelectorPropertyChanged; } }
這個比較簡單了,就是事件的訂閱和取消了
上面這些都是繼承Control寫的,如果要實現listbox這種需要item這種單項內容的,還要加入繼承ContentControl的item相應的屬性的方法,要是覺的直接繼承Control很多屬性和事件都被加進來太多的話還可以自己寫個DependencyProperty 和DependencyObject,詳細可以參考一下這篇DependencyObject,更深入的以后學習了在發