WP记录DependencyProperty学习(1)

很早之前就看到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,更深入的以后学习了在发

 

 

 

 

posted @ 2015-01-30 17:38  小槽君  阅读(1079)  评论(6编辑  收藏  举报