首页 > 技术文章 > 使用ToggleButton和StackPanel+Border实现圆角开关按钮动画效果

Events 2013-09-27 11:36 原文

<ToggleButton  Height="40"  Width="105" HorizontalAlignment="Left" Margin="138,122,0,0" Name="button1" VerticalAlignment="Top" Click="button1_Click">
            <ToggleButton.Content>
                <StackPanel Name="s1" Width="100" Height="22" Orientation="Horizontal" HorizontalAlignment="Left">
                    <Border Name="cd1" CornerRadius="10" BorderThickness="1" Width="100" BorderBrush="#FF001900">
                        <Border.Background>
                            <ImageBrush ImageSource="/MoveButton;component/Images/12.png" />
                        </Border.Background>
                    </Border>
                    <Border Name="cd2" CornerRadius="10" BorderThickness="1" Width="100" BorderBrush="#FF001900">
                        <Border.Background>
                            <ImageBrush ImageSource="/MoveButton;component/Images/13.png" />
                        </Border.Background>
                    </Border>
                </StackPanel>
            </ToggleButton.Content>
        </ToggleButton>
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (button1.IsChecked == true)
            {
                DoubleAnimation d1 = new DoubleAnimation();
                d1.From = 0;
                d1.To = 100;
                d1.Duration = new Duration(TimeSpan.Parse("0:0:0.2"));
                cd2.BeginAnimation(StackPanel.WidthProperty, d1);

                DoubleAnimation d2 = new DoubleAnimation();
                d2.From = 100;
                d2.To = 0;
                d2.Duration = new Duration(TimeSpan.Parse("0:0:0.2"));
                cd1.BeginAnimation(StackPanel.WidthProperty, d2);
            }

            if (button1.IsChecked == false)
            {
                DoubleAnimation d1 = new DoubleAnimation();
                d1.From = 100;
                d1.To = 0;
                d1.Duration = new Duration(TimeSpan.Parse("0:0:0.2"));
                cd2.BeginAnimation(StackPanel.WidthProperty, d1);

                DoubleAnimation d2 = new DoubleAnimation();
                d2.From = 0;
                d2.To = 100;
                d2.Duration = new Duration(TimeSpan.Parse("0:0:0.2"));
                cd1.BeginAnimation(StackPanel.WidthProperty, d2);
            }
        }

代码没精简,无图无真相,看看OFF和ON

推荐阅读