7

我想对BackgroundWPF 窗口的颜色进行颜色转换。

我怎样才能做到这一点?

例如:

Brush i_color = Brushes.Red; //this is the initial color
Brush f_color = Brushes.Blue; //this is the final color

当我点击Buttonbutton1

private void button1_Click(object sender, RoutedEventArgs e)
{
    this.Background = f_color; //here the transition begins. I don't want to be quick. Maybe an interval of 4 seconds.
}
4

4 回答 4

13

在代码中可以用这个来完成

private void button1_Click(object sender, RoutedEventArgs e)
{
    ColorAnimation ca = new ColorAnimation(Colors.Red, Colors.Blue, new Duration(TimeSpan.FromSeconds(4)));
    Storyboard.SetTarget(ca, this);
    Storyboard.SetTargetProperty(ca, new PropertyPath("Background.Color"));

    Storyboard stb = new Storyboard();
    stb.Children.Add(ca);
    stb.Begin();
}

正如 HB 指出的那样,这也可以

private void button1_Click(object sender, RoutedEventArgs e)
{
    ColorAnimation ca = new ColorAnimation(Colors.Blue, new Duration(TimeSpan.FromSeconds(4)));
    this.Background = new SolidColorBrush(Colors.Red);
    this.Background.BeginAnimation(SolidColorBrush.ColorProperty, ca);
}
于 2012-07-23T17:29:27.670 回答
5

这是一种方法:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

    <Grid x:Name="BackgroundGrid" Background="Red">

        <Button HorizontalAlignment="Left" VerticalAlignment="Top">
            Transition
            <Button.Triggers>
                <EventTrigger RoutedEvent="Button.Click">
                    <BeginStoryboard>
                        <Storyboard>
                            <ColorAnimation  Storyboard.TargetName="BackgroundGrid" From="Red" To="Blue" Duration="0:0:4" Storyboard.TargetProperty="Background" />
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </Button.Triggers>
        </Button>
    </Grid>
</Window>
于 2012-07-23T17:23:02.460 回答
3

您可以使用动画(阅读此内容),特别是 a ColorAnimation(参见示例)或ColorAnimationUsingKeyframes.

于 2012-07-23T17:19:59.777 回答
1

只是为了完成 LPL 和 HB 的回答.....在我的情况下,我需要将控件恢复为与动画之前相同的颜色。

这是我的代码

ColorAnimation animation = new ColorAnimation()
{
    From = Colors.Orange,
    To = ((SolidColorBrush)myControl.Background).Color,//Revert to initial control Color
    Duration = new Duration(TimeSpan.FromSeconds(2))
};

myControl.Background = new SolidColorBrush(Colors.Orange);//Do not use a frozen instance
myControl.Background.BeginAnimation(SolidColorBrush.ColorProperty, animation);
于 2013-10-21T14:50:33.040 回答