WPF中的颜色转换

Ion*_*zău 5 c# wpf xaml transition colors

我想要进行BackgroundWPF窗口颜色的颜色转换.

我怎样才能做到这一点?

例如:

Brush i_color = Brushes.Red; //this is the initial color
Brush f_color = Brushes.Blue; //this is the final color
Run Code Online (Sandbox Code Playgroud)

当我点击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.
}
Run Code Online (Sandbox Code Playgroud)

LPL*_*LPL 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();
}
Run Code Online (Sandbox Code Playgroud)

正如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);
}
Run Code Online (Sandbox Code Playgroud)

  • @LPL:你只需要确保*不*使用`SolidColorBrush`的冻结实例,例如将`Background`设置为`new SolidColorBrush(Colors.Red)`,然后设置动画.来自"画笔"的实例可能都被冻结,因此它们无法更改(这可能很奇怪,想象有人拿着'Brushes.Red`而现在它是蓝色的). (2认同)

RQD*_*QDQ 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>
Run Code Online (Sandbox Code Playgroud)