I can't animate a custom property in WPF - wpf

I've been struggling with this for hours and I can't find out what I'm doing wrong. Please help me find my mistake.
I created a user control with one custom dependency property and I want to animate this property.
Here is my class:
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public long Val
{
get { return (long)GetValue(ValProperty); }
set {
SetValue(ValProperty, value);
// Update a text block for debug
((Class1)this.Resources["class1"]).Val = value;
}
}
public static readonly DependencyProperty ValProperty =
DependencyProperty.Register("Val", typeof(long), typeof(UserControl1), new UIPropertyMetadata(0L));
}
Here is the code that is supposed to animate it (there's an instance of UserControl1 called usercontrol11):
Int64Animation myAnimation = new Int64Animation();
myAnimation.From = 100;
myAnimation.To = 200;
myAnimation.Duration = new Duration(TimeSpan.FromSeconds(1));
Storyboard.SetTargetName(myAnimation, userControl11.Name);
Storyboard.SetTargetProperty(myAnimation, new PropertyPath(UserControl1.ValProperty));
Storyboard myStoryboard = new Storyboard();
myStoryboard.Children.Add(myAnimation);
myStoryboard.Begin(this);
I also tried the XAML approach, but it didn't work either (in the following XAML, the Width animation works fine, but the Val doesn't):
<my:UserControl1 HorizontalAlignment="Left" Width="150" Margin="72,45,0,0" x:Name="userControl11" VerticalAlignment="Top" Background="#FFFFD100">
<my:UserControl1.Triggers>
<EventTrigger RoutedEvent="MouseEnter">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<Int64Animation To="300" Duration="0:0:1"
Storyboard.TargetProperty="Val" />
<DoubleAnimation To="300" Duration="0:0:1"
Storyboard.TargetProperty="Width" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</my:UserControl1.Triggers>
</my:UserControl1>
Any help will be much appreciated!

Well, it's actually animated. You're just checking in the wrong place, animation won't call Val property set accessor. You can, for example, override OnPropertyChanged method to see changes:
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
if(e.Property == ValProperty)
{
MessageBox.Show(e.NewValue.ToString());
}
}

Related

Can I use data-binding on the Duration of an Animation in a ControlTemplate?

I found a good explanation here on SO of how to bind the Duration property of a ColorAnimation to the Value property of a Slider. One uses a converter to convert the Double value from the slider to a Duration, and a Binding to have that set the Duration of the ColorAnimation. Here, abbreviated, is how that works:
<Window.Resources>
<local:DoubleToDurationConverter x:Key="DoubleToDurationConverter" />
</Window.Resources>
<Slider x:Name="slider" />
<Button Content="Click me for an animation">
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<BeginStoryboard>
<Storyboard>
<ColorAnimation To="Green"
Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)"
FillBehavior="Stop"
Duration="{Binding ElementName=slider,
Path=Value,
Mode=OneWay,
Converter={StaticResource DoubleToDurationConverter}}" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Button.Triggers>
</Button>
I tried that and it worked fine for me. But what I want to do is bind the Duration to a dependency property called FadeTime I've added to my custom control. So, in that control's ControlTemplate I have this:
<ControlTemplate.Triggers>
<Trigger Property="IsLit" Value="true">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="glow"
Storyboard.TargetProperty="Opacity"
To="1"
Duration="{Binding FadeTime, Mode=OneWay,
RelativeSource={RelativeSource TemplatedParent}}"/>
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
</Trigger>
</ControlTemplate.Triggers>
This compiles, but gives me an error message at run-time:
InvalidOperationException: Cannot freeze this Storyboard timeline tree
for use across threads.
How can I bind my DoubleAnimation's Duration to a dependency variable in a custom control's ControlTemplate?
Thanks!
UPDATE
Data-binding is actually gross overkill for what I want to do. Real data-binding would allow for the property's value to change at run-time. All I really want is a way for the developer who is using my custom control to be able to set the Duration of the DoubleAnimation at design time, without having to edit the ControlTemplate. It's okay if the value the developer chooses never changes at run time.
Instead of defining the animation in your XAML markup, you could define it programmatically in the PropertyChangedCallback for the IsLit property.
You could simply define another property that lets the consumer of the control specify the duration of the animation.
Here is an example for you.
Control:
public class MyCustomControl : Control
{
private UIElement glow;
public static readonly DependencyProperty DurationProperty =
DependencyProperty.Register("Duration", typeof(TimeSpan),
typeof(MyCustomControl), new PropertyMetadata(TimeSpan.FromSeconds(1)));
public TimeSpan Duration
{
get { return (TimeSpan)GetValue(DurationProperty); }
set { SetValue(DurationProperty, value); }
}
public static readonly DependencyProperty IsLitProperty =
DependencyProperty.Register("IsLit", typeof(bool),
typeof(MyCustomControl), new PropertyMetadata(false, new PropertyChangedCallback(OnIsLitChanged)));
public bool IsLit
{
get { return (bool)GetValue(IsLitProperty); }
set { SetValue(IsLitProperty, value); }
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
glow = Template.FindName("glow", this) as UIElement;
if (glow != null && IsLit)
Animate(glow);
}
private static void OnIsLitChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
bool newValue = (bool)e.NewValue;
if(newValue)
{
MyCustomControl c = d as MyCustomControl;
if(c != null && c.glow != null)
{
c.Animate(c.glow);
}
}
}
private void Animate(UIElement glow)
{
DoubleAnimation animation = new DoubleAnimation();
animation.To = 1;
animation.Duration = Duration;
glow.BeginAnimation(OpacityProperty, animation);
}
}
Template:
<ControlTemplate x:Key="ct" TargetType="local:MyCustomControl">
<Border x:Name="glow" Width="100" Height="100" Background="Red" Opacity="0.1">
</Border>
</ControlTemplate>
Usage:
<local:MyCustomControl Template="{StaticResource ct}" Duration="0:0:5" IsLit="True" />
Basically, you can't use normal bindings inside the storyboard of a control template. Since you just want a way for developers to change the value, one of the following options might work for you:
(1) Use StaticResource: Place a duration object somewhere outside the control template, where it's easier to change for developers. However, it needs to be somewhere statically accessible to the control template, since DynamicResource won't work in this place.
<Duration x:Key="MyCustomDuration">0:0:1</Duration>
... then later
Duration="{StaticResource MyCustomDuration}"
(2) Use a static code behind field with x:Static:
public static class SettingsClass
{
public static Duration MyCustomDuration = new Duration(new TimeSpan(0, 0, 1));
}
and use:
Duration="{x:Static local:SettingsClass.MyCustomDuration}"

WPF Animate property of child without using Name

I'm trying to create a storyboard in XAML that animates a property of one of the child elements of an element which raises an event. But I can't seem to get it to work without using Names, which is something I can't really do in this specific situation.
I'm basically trying something like this (much simplified of course):
<Canvas>
<Canvas.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="Children[0].(Canvas.Left)" From="0" To="400" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Canvas.Triggers>
<Button Canvas.Left="20" Canvas.Top="20">A</Button>
<Button Canvas.Left="40" Canvas.Top="20">B</Button>
</Canvas>
Any ideas on how this could be achieved?
Providing that the UIElement you are indexing in the animation exists (i.e. already present on the Canvas) then you can do the following:
<Canvas x:Name="MyCanvas">
<Button x:Name="btn" Canvas.Left="20" Canvas.Top="20">A</Button>
<Button Canvas.Left="40" Canvas.Top="20">B</Button>
<Canvas.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.Target="{Binding ElementName=MyCanvas, Path=Children[0]}"
Storyboard.TargetProperty="(Canvas.Left)" From="0" To="400" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Canvas.Triggers>
</Canvas>
Notice how I have moved the addition of the Buttons above the Trigger. If the Buttons are below the Trigger as in your question, trying to access Children[0] will throw an ArgumentOutOfRangeException because there are no children at this point.
To use the Storyboard.TargetProperty in the animation, it should always be a dependency property. Children property gets a UIElementCollection of child elements of this Panel (Canvas). Therefore, the following construction Children [n] return UIElement, which should lead to a certain type, to access its dependency property.
This can be done in the code as follows:
Button MyButton = (Button)MyCanvas.Children[0];
MessageBox.Show(MyButton.Width.ToString());
All of these actions missing in the animation by default, this is your construction will not work.
I propose to create animations in the code where this conversion possible.
To demonstrate this, I created a Canvas, in the event Loaded having registered animation. Element number is set via an attached dependency property (of course, the example can be implemented in various ways). Below is my example:
XAML
<Grid>
<local:MyCanvas x:Name="MyCanvas" local:ClassForAnimation.Children="1">
<Button Canvas.Left="20" Canvas.Top="20">A</Button>
<Button Canvas.Left="40" Canvas.Top="20">B</Button>
</local:MyCanvas>
</Grid>
Code behind
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
public class MyCanvas : Canvas
{
public MyCanvas()
{
this.Loaded += new RoutedEventHandler(MyCanvas_Loaded);
}
private void MyCanvas_Loaded(object sender, RoutedEventArgs e)
{
MyCanvas myCanvas = sender as MyCanvas;
// Get No. of children
int children = ClassForAnimation.GetChildren(myCanvas);
// Get current Button for animation
Button MyButton = (Button)myCanvas.Children[children];
if (myCanvas != null)
{
DoubleAnimation doubleAnimation = new DoubleAnimation();
doubleAnimation.From = 0;
doubleAnimation.To = 400;
MyButton.BeginAnimation(Button.WidthProperty, doubleAnimation);
}
}
}
public class ClassForAnimation : DependencyObject
{
public static readonly DependencyProperty ChildrenProperty;
public static void SetChildren(DependencyObject DepObject, int value)
{
DepObject.SetValue(ChildrenProperty, value);
}
public static int GetChildren(DependencyObject DepObject)
{
return (int)DepObject.GetValue(ChildrenProperty);
}
static ClassForAnimation()
{
PropertyMetadata MyPropertyMetadata = new PropertyMetadata(0);
ChildrenProperty = DependencyProperty.RegisterAttached("Children",
typeof(int),
typeof(ClassForAnimation),
MyPropertyMetadata);
}
}
Note: Access to the items in the Canvas should only be done in the event Loaded, or when it ended. Otherwise, the items are not available because they are not loaded.

Very strange problem in Silverlight with XAML, custom property and animation

I created a custom user control that has a property of type Storyboard. Something like:
public class UC : UserControl
{
public static readonly DependencyProperty AnimationProperty = DependencyProperty.Register(
"Animation",
typeof(Storyboard),
typeof(UC),
null);
public Storyboard Animation
{
get { return (Storyboard)GetValue(AnimationProperty); }
set { SetValue(AnimationProperty, value); }
}
public UC()
{
this.Loaded += new RoutedEventHandler(UC_Loaded);
}
private void UC_Loaded(object sender, RoutedEventArgs e)
{
if (this.Animation != null)
{
this.Animation.Begin();
}
}
}
In XAML I used it as follows:
<loc:UC x:Name="uc" Opacity="0" >
<TextBlock FontSize="50">Some text</TextBlock>
<loc:UC.Animation>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="uc" Storyboard.TargetProperty="Opacity" To="0.5" Duration="0:0:1" />
</Storyboard>
</loc:UC.Animation>
</loc:UC>
So far so good.
Later on I decided that I needed another item along with the storyboard. So I changed the code to accept a custom object that contains the storyboard and another piece of information. Something like:
public class UC : UserControl
{
public static readonly DependencyProperty AnimationProperty = DependencyProperty.Register(
"Animation",
typeof(AnimationHolder),
typeof(UC),
null);
public AnimationHolder Animation
{
get { return (AnimationHolder)GetValue(AnimationProperty); }
set { SetValue(AnimationProperty, value); }
}
public UC()
{
this.Loaded += new RoutedEventHandler(UC_Loaded);
}
private void UC_Loaded(object sender, RoutedEventArgs e)
{
if (this.Animation != null)
{
this.Animation.Animation.Begin();
}
}
}
public class AnimationHolder
{
public Storyboard Animation
{
get;
set;
}
public int OtherValue
{
get;
set;
}
}
And used it in XAML:
<loc:UC x:Name="uc" Opacity="0" >
<TextBlock FontSize="50">Some text</TextBlock>
<loc:UC.Animation>
<loc:AnimationHolder OtherValue="20">
<loc:AnimationHolder.Animation>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="uc" Storyboard.TargetProperty="Opacity" To="0.5" Duration="0:0:0" />
</Storyboard>
</loc:AnimationHolder.Animation>
</loc:AnimationHolder>
</loc:UC.Animation>
</loc:UC>
However, now when I try to begin the animation I get an InvalidOperationException with the message: "Cannot resolve TargetName uc."
Anyone has an idea why?
I know that in this example I can work around the problem by not using a custom object, and using another property instead. However this is a simplified version of my scenario, which focuses at the problem. In the real scenario I must use a custom object.
Two things need to be done with your new approach:
In AnimationHolder class, make Animation property a dependency property, just like it previously was.
Derive AnimationHolder class from DependencyObject. This is necessary so that you can make Animation a dependency property. Please remember that only classes deriving from DependencyObject can define dependency properties!
I think once you do these two things, it'll solve your problem!

Binding Source in MediaTimeline

I am trying to have the mediatimeline bind to a Uri like so:
<UserControl.Resources>
<Storyboard x:Key="myStoryboard">
<MediaTimeline Storyboard.TargetName="myMediaPlayer"
Source="{Binding MediaSource}"
RepeatBehavior="Forever" />
</Storyboard>
</UserControl.Resources>
<UserControl.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded">
<BeginStoryboard Storyboard="{StaticResource myStoryboard}" />
</EventTrigger>
</UserControl.Triggers>
<Grid>
<MediaElement x:Name="mymediaPlayer" />
</Grid>
However, when I do this, it says that I need to "Must Specify URI." Dispatcher exception. In the viewmodel, I have a property like:
public Uri MediaSource
{
get { return _mediaSource; }
set
{
if (_oscilloscopeSource != value)
{
_mediaSource= value;
OnPropertyChanged("MediaSource");
}
}
}
It seems as though when the media player is loaded, it doesn't read the source from the binding. What gives?
In the constructor, I have:
_mediaSource = new Uri(#"C:\someMovie.mov", UriKind.Absolute);
Thanks.
Update
Can't get this to work so shooting in the dark now. Does moving the trigger to MediaElement make a difference?
<MediaElement x:Name="myMediaPlayer">
<MediaElement.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded">
<BeginStoryboard Storyboard="{StaticResource myStoryboard}" />
</EventTrigger>
</MediaElement.Triggers>
</MediaElement>
I tried this out and it works for me. Possible reasons I can think of.
Do you have the DataContext set for the UserControl?
Setting _mediaSource directly won't call OnPropertyChanged since you're not setting the CLR property. Set MediaSource instead.
Your MediaElement is named mymediaPlayer and not myMediaPlayer as the TargetName. (Typo?)
Except for the MediaElement Name which I changed, my working xaml is identical to yours. This is my full code behind file
public partial class UserControl1 : UserControl, INotifyPropertyChanged
{
public UserControl1()
{
InitializeComponent();
MediaSource = new Uri("C:\\C1.MOV");
this.DataContext = this;
}
private Uri _mediaSource;
public Uri MediaSource
{
get
{
return _mediaSource;
}
set
{
_mediaSource = value;
OnPropertyChanged("MediaSource");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}

WPF MVVM Property Change Animation

I am looking for a clean way to start an animation that will have dynamic values. Basically I want to do an animation where an element changes width based on the data of another element. Say I have a TextBlock that's Text Property is Binding. When this property changes I want a visual element say a Rectangle for our sake to do a DoubleAnimation changing the width from previous value to the new value.
I am trying to stay away from putting code in my view if possible. I've looked into DataTriggers but they seem to require that you know what the value would be such as an Enum. In my case it is just the value changing that needs to trigger a storyboard and the animation would need to start at the current(previous) value and move nicely to the new value.
Any ideas. Maybe I just missed a property.
Here is the solution I ended up with. To do the Animation based on data in my ViewModel I used a DataTrigger. Below is my Style for the control.
<Style TargetType="Grid" x:Key="DetailRotation" >
<Style.Triggers>
<DataTrigger Binding="{Binding Path=AnimationState}" Value="New">
<DataTrigger.EnterActions>
<StopStoryboard BeginStoryboardName="EndAnimation" />
<BeginStoryboard Name="NewAnimation">
<Storyboard>
<ThicknessAnimation Storyboard.TargetProperty="Margin" From="0,30,0,0" To="0,0,0,0" Duration="0:0:1" />
<DoubleAnimation Storyboard.TargetProperty="Opacity" From="0" To="1" Duration="0:0:1" />
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
<DataTrigger.ExitActions>
</DataTrigger.ExitActions>
</DataTrigger>
<DataTrigger Binding="{Binding Path=AnimationState}" Value="End">
<DataTrigger.EnterActions>
<StopStoryboard BeginStoryboardName="NewAnimation" />
<BeginStoryboard Name="EndAnimation">
<Storyboard>
<ThicknessAnimation Storyboard.TargetProperty="Margin" From="0,0,0,0" To="0,-20,0,0" Duration="0:0:1"/>
<DoubleAnimation Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:1" />
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
</Style.Triggers>
</Style>
You could explore using Attached Properties to hook up the necessary logic to the Storyboard/Animation that you desire.
This won't necessarily stop you from having to write code, but it will keep it separated from the view and allow it to be re-used across multiple views.
Actually you want to bind the DoubleAnimation.ToProperty to the ViewModel property and animate actual control. The problem is animation should be continued when ToProperty changed. My solution encapsulate all this logic to a MarkupExtenstion which wraps a Binding.
public class AnimateBindingExtension : MarkupExtension {
static DependencyPropertyDescriptor dpd =
DependencyPropertyDescriptor.FromProperty(DoubleAnimation.ToProperty,
typeof(DoubleAnimation));
public AnimateBindingExtension(PropertyPath path) {
Path = path;
}
public bool ValidatesOnExceptions { get; set; }
public IValueConverter Converter { get; set; }
public object ConverterParamter { get; set; }
public string ElementName { get; set; }
public RelativeSource RelativeSource { get; set; }
public object Source { get; set; }
public bool ValidatesOnDataErrors { get; set; }
[ConstructorArgument("path")]
public PropertyPath Path { get; set; }
public object TargetNullValue { get; set; }
public override object ProvideValue(IServiceProvider serviceProvider) {
var valueProvider = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
if (valueProvider == null) {
throw new Exception("could not get IProviderValueTarget service.");
}
var bindingTarget = valueProvider.TargetObject as FrameworkElement;
var bindingProperty = valueProvider.TargetProperty as DependencyProperty;
if (bindingProperty == null || bindingTarget == null) {
throw new Exception();
}
var binding = new Binding {
Path = Path,
Converter = Converter,
ConverterParameter = ConverterParamter,
ValidatesOnDataErrors = ValidatesOnDataErrors,
ValidatesOnExceptions = ValidatesOnExceptions,
TargetNullValue = TargetNullValue
};
if (ElementName != null) binding.ElementName = ElementName;
else if (RelativeSource != null) binding.RelativeSource = RelativeSource;
else if (Source != null) binding.Source = Source;
// you can add a Duration property to this class and use it here
var anim = new DoubleAnimation {
Duration = new Duration(TimeSpan.FromSeconds(0.1)),
AccelerationRatio = 0.2,
DecelerationRatio = 0.8
};
// this can be a new subclass of DoubleAnimation that
// overrides ToProperty metadata and add a property
// change callback
dpd.AddValueChanged(anim, (s, e) => bindingTarget.BeginAnimation(bindingProperty, anim));
BindingOperations.SetBinding(anim, DoubleAnimation.ToProperty, binding);
// this is because we need to catch the DataContext so add animation object
// to the visual tree by adding it to target object's resources.
bindingTarget.Resources[bindingProperty.Name] = anim;
// animation will set the value
return DependencyProperty.UnsetValue;
}
}
You can do the same with other animation classes to animate other types.
Since properties modified by animation cannot be set outside the animation 'context', I came up with a code solution since I could not do the same in XAML effectively.
private void UserControl_IsVisibleChanged(object sender,
DependencyPropertyChangedEventArgs e)
{
if (this.Visibility == Visibility.Visible)
{
DoubleAnimation fadeIn = new DoubleAnimation();
fadeIn.From = 1d;
fadeIn.To = 1d;
fadeIn.Duration = new Duration(new TimeSpan(0, 0, 0));
DoubleAnimation fade = new DoubleAnimation();
fade.From = 1d;
fade.To = 0d;
fade.BeginTime = TimeSpan.FromSeconds(5);
fade.Duration = new Duration(new TimeSpan(0, 0, 1));
NameScope.SetNameScope(this, new NameScope());
this.RegisterName(this.Name, this);
Storyboard.SetTargetName(fadeIn, this.Name);
Storyboard.SetTargetProperty(fadeIn, new PropertyPath
(UIElement.OpacityProperty));
Storyboard.SetTargetName(fade, this.Name);
Storyboard.SetTargetProperty(fade, new PropertyPath
(UIElement.OpacityProperty));
Storyboard sb = new Storyboard();
sb.Children.Add(fadeIn);
sb.Children.Add(fade);
sb.Completed += new EventHandler(sb_Completed);
sb.Begin(this);
}
}
void sb_Completed(object sender, EventArgs e)
{
this.Visibility = Visibility.Hidden;
}

Resources