从一种风格到另一种风格的动画

时间:2009-07-26 11:57:41

标签: wpf animation triggers styles

只是想知道是否有人知道如何从一种风格动画到另一种风格,即当用户专注于文本框时从NormalStyle转到ActiveStyle

<Style x:key="NormalStyle" TargetType="{x:Type TextBox}">
    <Setter Property="BorderBrush" Value="Gray" />
    <Setter Property="BorderThickness" Value="2" />
</Style>

<Style x:key="ActiveStyle" TargetType="{x:Type TextBox}" BasedOn="{StaticResource NormalStyle}">
    <Setter Property="BorderBrush" Value="Green" /> 
    <Setter Property="BorderThickness" Value="4" />
</Style>

1 个答案:

答案 0 :(得分:1)

如果你想交换整个风格,我想你可能必须在代码中这样做:

<StackPanel>
    <TextBox Style="{StaticResource NormalStyle}" GotFocus="TextBox_GotFocus" LostFocus="TextBox_LostFocus"/>
    <TextBox Style="{StaticResource NormalStyle}" GotFocus="TextBox_GotFocus" LostFocus="TextBox_LostFocus"/>
</StackPanel>
    private Style focusedStyle;
    private Style normalStyle;

    public MainWindow()
    {
        InitializeComponent();

        focusedStyle = FindResource("ActiveStyle") as Style;
        normalStyle = FindResource("NormalStyle") as Style;
    }

    private void TextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        ((TextBox)sender).Style = focusedStyle;
    }

    private void TextBox_LostFocus(object sender, RoutedEventArgs e)
    {
        ((TextBox)sender).Style = normalStyle;
    }

否则,你几乎只能来回触发..

<TextBox Text="1" >
        <TextBox.Style>
            <Style BasedOn="{StaticResource NormalStyle}" TargetType="{x:Type TextBox}">
                <Style.Triggers>
                    <EventTrigger RoutedEvent="GotFocus">
                        <BeginStoryboard>
                            <Storyboard>
                                <ColorAnimation Storyboard.TargetProperty="BorderBrush.Color" To="Green" Duration="0:0:0.1" />
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                    <EventTrigger RoutedEvent="LostFocus">
                        <BeginStoryboard>
                            <Storyboard>
                                <ColorAnimation Storyboard.TargetProperty="BorderBrush.Color" To="Gray" Duration="0:0:0.1" />
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                </Style.Triggers>
            </Style>
        </TextBox.Style