silverlight中的ContentPresent,TemplateBinding和VisualStateManager使用教程

   ContentPresent:

       如果ContentPresent对象是存在于ContentControl的ControlTemplate中,那么就ContentPresent会自动绑定到Content与ContentTemplate,比如

Tooltip是继承自ContentControl的:

      image

   那么我们上面的ContentPresent中就可以省略Content与ContentTemplate的绑定,可以直接写成

<ContentPresenter  Cursor="{TemplateBinding Cursor}"   Margin="{TemplateBinding Padding}"/>

同样的,如果我们使用位于ItemsControl的ControlTemplate 中的 ItemsPresenter ,其将自动绑定到 Items和ItemsPresenter属性。

   TemplateBinding

         TemplateBinding将ControlTemplate 中元素的属性绑定到由控件定义的公共属性。创建好一个ControlTemplate后,如果在ContentPresenter中,设置了一

个值后,那么你设置控件的属性是不会产生任何影响的。

    <ContentPresenter  Cursor="Hand"   Margin="{TemplateBinding Padding}"/>

         这里我们将上面的ControlPresenter中的Cursor设置为Hand,那么对应用了该ControlTemplate的ToolTip,无论设置Cursor为何值,移到内容显示区域时

显示出来的图标都是Hand。

         在Control类中定义了一些可以由ControlTemlate使用的可视属性        image

         尽管我们在上面的ContentTemplate中并没有显示的设置Foreground,但是当我们改变Tooltip的Foreground的值时,可以看到效果有所变化,因为

Foreground是继承而来的,尽管并没有使用{TemplateBinding Foreground}

         从图中也可以看出来ControlTemplate可以通过两种方式使用这些属性,除了这些可视属性,还可以继承父元素的DataContext,Language,TextDercoration。

  VisualStateManager

        上面仅仅是讲ControlTemplate使得XAML元素的外观比较灵活的方式呈现,Silverlight中每个控件有默认的视觉效果,并且可以改变默认效果,

这主要应用了VisualStateManager特性

        VisualState 对象可指定控件在处于特定状态时的外观

image        VisualState 中包含了Storyboard,可用于更改ControlTemplate中元素的外观,控件进入 VisualState.Name 属性指定的状态时,动画开始工作,

控件退出该状态时,动画停止。

        XAML一般如下定义:

        <vsm:VisualState x:Name="Closed">

            <Storyboard>

            <ColorAnimation ...></ColorAnimation>

            </Storyboard>

        </vsm:VisualState>

      上面的表示的是ToolTip关闭时的动画,  VisualState的Name要与ToolTip上的TemplateVisualStateAttribute相匹配

image     VisualState可被添加至VisualStateGroup 对象中

        <VisualStateGroup x:Name="OpenStates">

                                    <vsm:VisualState x:Name="Closed">

                                        <Storyboard>

                                            <ColorAnimation ...></ColorAnimation>

                                        </Storyboard>

                                    </vsm:VisualState>

                                    <vsm:VisualState x:Name="Open">

                                        <Storyboard>

                                            <ColorAnimation ...></ColorAnimation>

                                        </Storyboard>

                                    </vsm:VisualState>

        </VisualStateGroup>

    VisualStateGroup 可被添加到 VisualStateManager.VisualStateGroups这个附加属性中,其必须在ControlTemplate中的根FrameworkElement进行设置。

        <ControlTemplate TargetType="ToolTip">

             <Border>

                    <VisualStateManager.VisualStateGroups>

                          ...

                     </VisualStateManager.VisualStateGroups>   

             </Border>

        </ControlTemplate>

共有0个回答