2013-01-04 44 views
33

Tôi cần trợ giúp trong việc đưa ra quyết định đúng. Tôi cần tạo hiệu ứng nền cho điều khiển người dùng khi một số sự kiện xảy ra. Khi đó, tôi muốn thay đổi nền chỉ trong 1 giây và sau đó quay lại. Tôi nên đi con đường nào? Sử dụng hoạt ảnh màu hoặc hẹn giờ hoặc có thể theo một cách khác.Wpf nền màu animate

Đã giải quyết. Cảm ơn tất cả! Điều này phù hợp với tôi:

 ColorAnimation animation; 
     animation = new ColorAnimation(); 
     animation.From = Colors.Orange; 
     animation.To = Colors.Gray; 
     animation.Duration = new Duration(TimeSpan.FromSeconds(1)); 
     this.elGrid.Background.BeginAnimation(SolidColorBrush.ColorProperty, animation); 
+0

rất cởi mở vì nó có xu hướng là lựa chọn cá nhân hơn. Tôi khuyên bạn nên tái diễn đạt câu hỏi hoặc bao gồm những điều bạn đã thử. – Backlash

+0

im xin lỗi tôi đã thêm một thẻ "animate" có vẻ như nó được thay đổi tự động. – Taras

+0

Bạn nên đăng ít nhất một số mã/thông tin khác (sự kiện nào? Hình xaml của bạn trông như thế nào?) –

Trả lời

49

Tôi sẽ sử dụng một EventTrigger với một ColorAnimation.

Trong ví dụ này, Button Brackground chuyển sang màu xanh lục trên sự kiện MouseLeave. Mã này hy vọng tương tự như những gì bạn có thể cần.

<Button Content="Button" Height="75" HorizontalAlignment="Left" Margin="27,12,0,0" Name="btnImgBrush" VerticalAlignment="Top" Width="160" Background="LightGray"> 
    <Button.Triggers> 
     <EventTrigger RoutedEvent="Button.MouseLeave"> 
      <BeginStoryboard> 
       <Storyboard> 
        <ColorAnimation To="Green" 
            Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)" 
            FillBehavior="Stop" 
            Duration="0:0:1"/> 
       </Storyboard> 
      </BeginStoryboard> 
     </EventTrigger> 
    </Button.Triggers> 
</Button> 
+1

Tôi nhận được XAML không hợp lệ, nên '' 'Duration''' là' '' 0: 0: 1''' thay thế? –

+0

có bạn đã đúng. Tôi sửa nó rồi. Cảm ơn – Klaus78

+10

@ Klaus78 (Nút.Background) (SolidColorBrush.Color) có nghĩa là gì? Vai trò ngoặc đơn ở đây là gì ?? – Helic

0

Trong WPF, Sử dụng hoạt ảnh có thể tốt hơn. Cụm từ biểu thức có hoạt ảnh/hành vi tương đối.

-7

Bạn có thể sử dụng DoubleAnimation để thay đổi màu sắc như thế này:

<Storyboard> 
    <DoubleAnimation Storyboard.TargetProperty="Background" 
          From="0.0" 
          Duration="0:0:2" 
          To="1.0" />       
</Storyboard> 

Hy vọng nó giúp

+2

thực sự Nền là kiểu Brush. DoubleAnimation được sử dụng để tạo hoạt ảnh cho các loại tăng gấp đôi. – Klaus78

+0

Điều đó đúng với Kaus78. Tôi trích đoạn này từ một trong các ControlTemplate mà tôi đã định nghĩa trước đó cho một điều khiển Label và thay thế Opacity bằng Background chỉ cho một ví dụ nhanh. – Iftikhar

21

Xem ra, bạn có thể nhận được System.InvalidOperationException nếu nền của bạn là trường hợp cố định.

Không thể tạo hoạt ảnh 'Màu' trên 'System.Windows.Media.SolidColorBrush' vì đối tượng bị đóng kín hoặc đóng băng.

Để sửa thông báo này, hãy gán nền điều khiển cho trường hợp không được cố định.

// Do not use a frozen instance 
this.elGrid.Background = new SolidColorBrush(Colors.Orange); 
this.elGrid.Background.BeginAnimation(SolidColorBrush.ColorProperty, animation); 

Freezable Objects Overview on MSDN

+1

Điều này phải có trong mã được thêm vào câu hỏi gốc. – fbmd

5
 ColorAnimation colorChangeAnimation = new ColorAnimation(); 
     colorChangeAnimation.From = VariableColour; 
     colorChangeAnimation.To = BaseColour; 
     colorChangeAnimation.Duration = timeSpan; 

     PropertyPath colorTargetPath = new PropertyPath("(Panel.Background).(SolidColorBrush.Color)"); 
     Storyboard CellBackgroundChangeStory = new Storyboard(); 
     Storyboard.SetTarget(colorChangeAnimation, BackGroundCellGrid); 
     Storyboard.SetTargetProperty(colorChangeAnimation, colorTargetPath); 
     CellBackgroundChangeStory.Children.Add(colorChangeAnimation); 
     CellBackgroundChangeStory.Begin(); 

// VariableColour & BaseColour là lớp màu, TimeSpan là Lớp TimeSpan, BackGroundCellGrid là lớp lưới;

// không cần tạo SolidColorBrush và liên kết với nó trong XAML; //chúc vui vẻ!

1

Dưới đây là một tập hợp các thuộc tính đính kèm có thể được sử dụng nếu bạn gặp sự cố với các tệp có thể lưu trữ.

using System; 
using System.ComponentModel; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Media; 
using System.Windows.Media.Animation; 
using System.Windows.Shapes; 

public static class Blink 
{ 
    public static readonly DependencyProperty WhenProperty = DependencyProperty.RegisterAttached(
     "When", 
     typeof(bool?), 
     typeof(Blink), 
     new PropertyMetadata(false, OnWhenChanged)); 

    public static readonly DependencyProperty FromProperty = DependencyProperty.RegisterAttached(
     "From", 
     typeof(Color), 
     typeof(Blink), 
     new FrameworkPropertyMetadata(Colors.Transparent, FrameworkPropertyMetadataOptions.Inherits)); 

    public static readonly DependencyProperty ToProperty = DependencyProperty.RegisterAttached(
     "To", 
     typeof(Color), 
     typeof(Blink), 
     new FrameworkPropertyMetadata(Colors.Orange, FrameworkPropertyMetadataOptions.Inherits)); 

    public static readonly DependencyProperty PropertyProperty = DependencyProperty.RegisterAttached(
     "Property", 
     typeof(DependencyProperty), 
     typeof(Blink), 
     new PropertyMetadata(default(DependencyProperty))); 

    public static readonly DependencyProperty DurationProperty = DependencyProperty.RegisterAttached(
     "Duration", 
     typeof(Duration), 
     typeof(Blink), 
     new PropertyMetadata(new Duration(TimeSpan.FromSeconds(1)))); 

    public static readonly DependencyProperty AutoReverseProperty = DependencyProperty.RegisterAttached(
     "AutoReverse", 
     typeof(bool), 
     typeof(Blink), 
     new PropertyMetadata(true)); 

    public static readonly DependencyProperty RepeatBehaviorProperty = DependencyProperty.RegisterAttached(
     "RepeatBehavior", 
     typeof(RepeatBehavior), 
     typeof(Blink), 
     new PropertyMetadata(RepeatBehavior.Forever)); 

    private static readonly DependencyProperty OldBrushProperty = DependencyProperty.RegisterAttached(
     "OldBrush", 
     typeof(Brush), 
     typeof(Blink), 
     new PropertyMetadata(null)); 

    public static void SetWhen(this UIElement element, bool? value) 
    { 
     element.SetValue(WhenProperty, value); 
    } 

    [AttachedPropertyBrowsableForChildren(IncludeDescendants = false)] 
    [AttachedPropertyBrowsableForType(typeof(UIElement))] 
    public static bool? GetWhen(this UIElement element) 
    { 
     return (bool?)element.GetValue(WhenProperty); 
    } 

    public static void SetFrom(this DependencyObject element, Color value) 
    { 
     element.SetValue(FromProperty, value); 
    } 

    [AttachedPropertyBrowsableForChildren(IncludeDescendants = false)] 
    [AttachedPropertyBrowsableForType(typeof(UIElement))] 
    public static Color GetFrom(this DependencyObject element) 
    { 
     return (Color)element.GetValue(FromProperty); 
    } 

    public static void SetTo(this DependencyObject element, Color value) 
    { 
     element.SetValue(ToProperty, value); 
    } 

    [AttachedPropertyBrowsableForChildren(IncludeDescendants = false)] 
    [AttachedPropertyBrowsableForType(typeof(UIElement))] 
    public static Color GetTo(this DependencyObject element) 
    { 
     return (Color)element.GetValue(ToProperty); 
    } 

    public static void SetProperty(this UIElement element, DependencyProperty value) 
    { 
     element.SetValue(PropertyProperty, value); 
    } 

    [AttachedPropertyBrowsableForChildren(IncludeDescendants = false)] 
    [AttachedPropertyBrowsableForType(typeof(UIElement))] 
    public static DependencyProperty GetProperty(this UIElement element) 
    { 
     return (DependencyProperty)element.GetValue(PropertyProperty); 
    } 

    public static void SetDuration(this UIElement element, Duration value) 
    { 
     element.SetValue(DurationProperty, value); 
    } 

    [AttachedPropertyBrowsableForChildren(IncludeDescendants = false)] 
    [AttachedPropertyBrowsableForType(typeof(UIElement))] 
    public static Duration GetDuration(this UIElement element) 
    { 
     return (Duration)element.GetValue(DurationProperty); 
    } 

    public static void SetAutoReverse(this UIElement element, bool value) 
    { 
     element.SetValue(AutoReverseProperty, value); 
    } 

    [AttachedPropertyBrowsableForChildren(IncludeDescendants = false)] 
    [AttachedPropertyBrowsableForType(typeof(UIElement))] 
    public static bool GetAutoReverse(this UIElement element) 
    { 
     return (bool)element.GetValue(AutoReverseProperty); 
    } 

    public static void SetRepeatBehavior(this UIElement element, RepeatBehavior value) 
    { 
     element.SetValue(RepeatBehaviorProperty, value); 
    } 

    [AttachedPropertyBrowsableForChildren(IncludeDescendants = false)] 
    [AttachedPropertyBrowsableForType(typeof(UIElement))] 
    public static RepeatBehavior GetRepeatBehavior(this UIElement element) 
    { 
     return (RepeatBehavior)element.GetValue(RepeatBehaviorProperty); 
    } 

    private static void OnWhenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     var property = GetProperty((UIElement)d) ?? GetDefaultProperty(d); 
     if (property == null || !typeof(Brush).IsAssignableFrom(property.PropertyType)) 
     { 
      if (DesignerProperties.GetIsInDesignMode(d)) 
      { 
       if (property != null) 
       { 
        throw new ArgumentException($"Could not blink for {d.GetType().Name}.{property.Name}", nameof(d)); 
       } 
      } 

      return; 
     } 

     AnimateBlink(e.NewValue as bool?, (UIElement)d, property); 
    } 

    private static DependencyProperty GetDefaultProperty(DependencyObject d) 
    { 
     if (d is Control) 
     { 
      return Control.BackgroundProperty; 
     } 

     if (d is Panel) 
     { 
      return Panel.BackgroundProperty; 
     } 

     if (d is Border) 
     { 
      return Border.BackgroundProperty; 
     } 

     if (d is Shape) 
     { 
      return Shape.FillProperty; 
     } 

     if (DesignerProperties.GetIsInDesignMode(d)) 
     { 
      throw new ArgumentException($"Could not find property to blink for {d.GetType().Name}", nameof(d)); 
     } 

     return null; 
    } 

    private static void AnimateBlink(bool? blink, UIElement element, DependencyProperty property) 
    { 
     if (element == null) 
     { 
      return; 
     } 
     if (blink == true) 
     { 
      var brush = element.GetValue(property); 
      element.SetCurrentValue(OldBrushProperty, brush); 
      element.SetValue(property, Brushes.Transparent); 
      var from = element.GetFrom(); 
      var to = element.GetTo(); 
      var sb = new Storyboard(); 
      var duration = element.GetDuration(); 
      var animation = new ColorAnimation(from, to, duration) 
      { 
       AutoReverse = element.GetAutoReverse(), 
       RepeatBehavior = element.GetRepeatBehavior() 
      }; 
      Storyboard.SetTarget(animation, element); 
      Storyboard.SetTargetProperty(animation, new PropertyPath($"{property.Name}.(SolidColorBrush.Color)")); 
      sb.Children.Add(animation); 
      sb.Begin(); 
     } 
     else 
     { 
      var brush = element.GetValue(OldBrushProperty); 
      element.BeginAnimation(property, null); 
      element.SetCurrentValue(property, brush); 
     } 
    } 
} 

Cách sử dụng:

<Grid> 
    <Grid.Resources> 
     <Style x:Key="BlinkWhenMouseOver" 
       TargetType="{x:Type Border}"> 
      <Setter Property="local:Blink.When" Value="{Binding IsMouseOver, RelativeSource={RelativeSource Self}}" /> 
      <Setter Property="local:Blink.From" Value="Honeydew" /> 
      <Setter Property="local:Blink.To" Value="HotPink" /> 
      <Setter Property="BorderThickness" Value="5" /> 
      <Setter Property="local:Blink.Property" Value="{x:Static Border.BorderBrushProperty}" /> 
     </Style> 
    </Grid.Resources> 
    <Grid.RowDefinitions> 
     <RowDefinition /> 
     <RowDefinition /> 
     <RowDefinition /> 
    </Grid.RowDefinitions> 
    <Border Style="{StaticResource BlinkWhenMouseOver}" Background="Transparent"/> 
    <Border Grid.Row="1" 
      local:Blink.From="Aqua" 
      local:Blink.To="Yellow" 
      local:Blink.When="{Binding IsChecked, 
             ElementName=ToggleBlink}" /> 
    <ToggleButton x:Name="ToggleBlink" 
        Grid.Row="2" 
        Content="Blink" /> 
</Grid> 
0

bài này đã giúp tôi. Nhưng nếu thay đổi màu sau 1 giây như câu hỏi ban đầu,

ColorAnimation animation; 
    animation = new ColorAnimation(); 
    animation.AutoReverse =true; 
0

Điều này làm việc tốt cho tôi.

Tôi có một con đường bên trong một nút (nó rút ra một chữ "X"):

<Path x:Name="MyDeleteRowButton" Stroke="Gray" Grid.Row="0" 
     Data="M1,5 L11,15 M1,15 L11,5" StrokeThickness="2" HorizontalAlignment="Center" 
     Stretch="None"/> 

On chuột lên, tôi muốn thập tự giá để đi màu đỏ, vì vậy tôi thêm:

<DataTemplate.Triggers> 
    <!-- Highlight row on mouse over, and highlight the delete button. --> 
    <EventTrigger RoutedEvent="ItemsControl.MouseEnter"> 
     <EventTrigger.Actions> 
      <BeginStoryboard> 
       <Storyboard> 
        <!-- On mouse over, flicker the row to highlight it.--> 
        <DoubleAnimation 
         Storyboard.TargetProperty="Opacity" 
         From="0.5" 
         To="1" 
         Duration="0:0:0.250" 
         FillBehavior="Stop"/> 
        <!-- Highlight the delete button with red. --> 
        <ColorAnimation 
         To="Red" 
         Storyboard.TargetName="MyDeleteRowButton" 
         Storyboard.TargetProperty="(Stroke).(SolidColorBrush.Color)" 
         Duration="0:0:0.100" 
         FillBehavior="HoldEnd"/> 
       </Storyboard> 
      </BeginStoryboard> 
     </EventTrigger.Actions> 
    </EventTrigger> 

    <!-- Grey out the delete button. --> 
    <EventTrigger RoutedEvent="ItemsControl.MouseLeave"> 
     <EventTrigger.Actions> 
      <BeginStoryboard> 
       <Storyboard> 
        <!-- Space is precious: "delete" button appears only on a mouseover. --> 
        <ColorAnimation 
         To="Gray" 
         Storyboard.TargetName="MyDeleteRowButton" 
         Storyboard.TargetProperty="(Stroke).(SolidColorBrush.Color)" 
         Duration="0:0:0.100" 
         FillBehavior="HoldEnd"/> 
       </Storyboard> 
      </BeginStoryboard> 
     </EventTrigger.Actions> 
    </EventTrigger> 

</DataTemplate.Triggers> 

Điều khó hiểu nhất về điều này là các dấu ngoặc trong phạm vi Storyboard.TargetProperty. Nếu bạn loại bỏ các dấu ngoặc, không có gì hoạt động.

Để biết thêm thông tin, hãy xem "propertyName Grammar" và "Storyboard.TargetProperty". Câu hỏi