WPF Styles,BasedOn,&故事板

时间:2009-09-22 20:02:53

标签: wpf triggers styles

我正在尝试创建一个简单的样式,突出显示焦点的UI元素(文本框,组合等),同时它具有焦点,并在失去焦点时消失。

我想出了这个:`

    <Style TargetType="{x:Type FrameworkElement}" x:Key="OnFocus">
        <Setter Property="Effect">
            <Setter.Value>
                <DropShadowEffect Color="Red" 
                        BlurRadius="0" 
                        ShadowDepth='0' />
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <EventTrigger RoutedEvent="UIElement.GotFocus">
                    <BeginStoryboard  Name="highlight">
                        <Storyboard>
                            <DoubleAnimation  
              Storyboard.TargetProperty="(UIElement.Effect).(DropShadowEffect.BlurRadius)" 
                           To="8" 
                           Duration="0:0:0.5" />
                        </Storyboard>
                    </BeginStoryboard>

                </EventTrigger>
            <EventTrigger RoutedEvent="UIElement.LostFocus">
                <RemoveStoryboard  BeginStoryboardName="highlight"></RemoveStoryboard>
            </EventTrigger>

        </Style.Triggers>


    </Style>`

但是如果我尝试创建简单的BasedOn样式,它就找不到BeginStoryboardName =“highlight”,所以每个元素最终都有整个Style.Triggers。

有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

由于样式不像OO继承那样继承,因此嵌套样式无法在其范围内找到故事板。

完成突出显示的最简单方法是添加第二个故事板,以反转突出显示。

<Storyboard x:Key="startHighlight" >
            <DoubleAnimation
                Storyboard.TargetProperty="(UIElement.Effect).(DropShadowEffect.BlurRadius)"
                To="8"
                Duration="0:0:0.5" />
        </Storyboard>
        <Storyboard x:Key="reverseHighlight"  >
            <DoubleAnimation
                Storyboard.TargetProperty="(UIElement.Effect).(DropShadowEffect.BlurRadius)"
                To="0"
                Duration="0:0:0.2" />
        </Storyboard>

        <Style TargetType="{x:Type FrameworkElement}">
            <Setter Property="Effect">
                <Setter.Value>
                    <DropShadowEffect Color="Red"
                                      BlurRadius="0"
                                      ShadowDepth="0" />
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <EventTrigger RoutedEvent="UIElement.GotFocus">
                    <BeginStoryboard  Storyboard="{StaticResource startHighlight}">
                    </BeginStoryboard>
                </EventTrigger>
                <EventTrigger RoutedEvent="UIElement.LostFocus">
                    <BeginStoryboard Storyboard="{StaticResource reverseHighlight}">
                    </BeginStoryboard>
                </EventTrigger>
            </Style.Triggers>
        </Style>
        <Style BasedOn="{StaticResource {x:Type FrameworkElement}}" TargetType="{x:Type TextBox}">

        </Style>