WPF中的颜色转换

时间:2012-07-23 17:11:35

标签: c# wpf xaml colors transition

我想要对WPF窗口的Background颜色进行颜色转换。

我该怎么做?

例如:

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

点击Button按钮1

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 个答案:

答案 0 :(得分: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();
}

H.B.指出这也会起作用

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);
}

答案 1 :(得分: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>

答案 2 :(得分:3)

您可以使用animation(请阅读此内容),特别是ColorAnimation(请参阅示例)或ColorAnimationUsingKeyframes

答案 3 :(得分:1)

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

这是我的代码

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);