Question Prelude :
How can I animate the Angle Property of a RotateTransform of
an UIElement A when the value of a Custom DependencyProperty
of type boolean becomes True when I click on an
UIElement B, all inside an UserControl ?
And in XAML ONLY (or mostly) ? if possible :)
I've written all the following to provide all the required details of my issue. You can stop reading from top to bottom anytime; even directly jump to the actual question, which is within the first quarter of the post.
Context :
The question is about Animation Triggers and Custom Property Binding, all within a single UserControl. No Window involved so far.
To begin with, let's assume I created an UserControl, which has a main Grid that contains two other Grids. Simpliest schemas :
<!-- MyControl.xaml -->
<UserControl ...blahblahblah>
<Grid>
<Grid x:Name="TiltingGrid">
<!-- This Grid contains UIElements that I want to tilt alltogether -->
</Grid>
<Grid>
<Ellipse x:Name="TiltingTrigger" ...blahblahblah>
<!-- This Ellipse is my "click-able" area -->
</Ellipse>
</Grid>
</Grid>
</UserControl>
Then, in Code Behind, I have a DependencyProperty called IsTilting.
// MyControl.xaml.cs
public bool IsTilting
{
// Default value is : false
get { return (bool)this.GetValue(IsTiltingProperty); }
set { this.SetValue(IsTiltingProperty, value); }
}
private static readonly DependencyProperty IsTiltingProperty =
DependencyProperty.Register(
"IsTilting",
typeof(bool),
typeof(MyControl),
new FrameworkPropertyMetadata(
false,
new PropertyChangedCallback(OnIsTiltingPropertyChanged)));
private static void OnIsTiltingPropertyChanged(...) { ... }
// .. is a classic Callback which calls
// private void OnIsTiltingChanged((bool)e.NewValue)
// and/or
// protected virtual void OnIsTiltingChanged(e) ...
Then, I defined some Properties for my Grid named TiltingGrid in the XAML :
<Grid x:Name="TiltingGrid"
RenderTransformOrigin="0.3, 0.5">
<Grid.RenderTransform>
<RotateTransform
x:Name="TiltRotate" Angle="0.0" />
<!-- Angle is the Property I want to animate... -->
</Grid.RenderTransform>
<!-- This Grid contains UIElements -->
<Path ... />
<Path ... />
<Ellipse ... />
</Grid>
And I would like to trigger the tilting upon clicking on a specific area inside this UserControl : An Ellipse, in the secund Grid :
<Grid>
<Ellipse x:Name="TiltingTrigger"
... Fill and Stroke goes here ...
MouseLeftButtonDown="TryTilt_MouseLeftButtonDown"
MouseLeftButtonUp="TryTilt_MouseLeftButtonUp">
</Ellipse>
</Grid>
If I'm not mistaken, Ellipse doesn't have a Click Event, so I had to create two EventHandlers for MouseLeftButtonDown and MouseLeftButtonUp. I had to do it that way to be able to :
Make the Ellipse capture Mouse upon MouseLeftButtonDown, and set a private field to true
Test whether the Mouse Point is inside the Ellipse upon MouseLeftButtonUp, set the value of the private field to false, then Release the Mouse.
Invert the value of the DependencyProperty IsTilting (true/false) if something looking like a "Click" occurs (..which would trigger the tilting animation if I'm able to resolve the appropriate Binding..)
I'll save you the MouseLeftDown/Up code, but I can provide it if required. What they do is to change the value of the DP.
Issue(s) :
I don't know how to trigger the Angle Animation when my DependencyProperty is updated. Well. That's not an actual issue, it's a lack of knowledge I reckon :
I don't know how to capture a custom event to be used with <EventTrigger>
I don't know how and where to trigger a StoryBoard using a True/False DependencyProperty.
And the actual question is :
From now on, how do I declare the code that makes the Angle
Property of the RotateTransform to animate from 0.0 to
45.0 (Rendering Transform of my Grid "TiltingGrid") when my DP IsTilting is set to true, and animate back to 0.0
when it's False ?
mostly in XAML way ..?
I do have a working code in C# code behind (detailed below) What I'm looking for is a workable solution in XAML (because it's usually very easy to rewrite almost anything in CodeBehind when you know how to do it in XAML)
What I tried so far...
From now on, you don't have to read further unless you absolutely want to know all the details...
1) Triggering the animation using natively defined Ellipse EventTriggers works only for Events defined for this specific UIElement (Enter/Leave/MouseLeftDown...) Done that alot with many UIElements.
But those triggers are not the ones I need : My Grid should tilt based on an On/Off or True/False custom state in a DP, not when something like a Mouse activity occurs.
<Ellipse.Triggers>
<EventTrigger RoutedEvent="UIElement.MouseEnter">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetName="TiltRotate"
Storyboard.TargetProperty="Angle"
From="0.0" To="45.0"
Duration="0:0:0.2" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="UIElement.MouseLeave">
...
</Ellipse.Triggers>
When the mouse enters the Ellipse, my Grid is tilting accordingly, but hence, How do I have access to custom Events defined in my UserControl ?
2) Then, based on the above scheme, I supposed I just had to create a Routed Event on my MyControl Class, or two, actually :
TiltingActivated
TiltingDisabled
.
public static readonly RoutedEvent TiltingActivatedEvent =
EventManager.RegisterRoutedEvent(
"TiltingActivated",
RoutingStrategy.Bubble,
typeof(RoutedEventHandler),
typeof(EventHandler));
public event RoutedEventHandler TiltingActivated
{
add { AddHandler(MyControl.TiltingActivatedEvent, value); }
remove { RemoveHandler(MyControl.TiltingActivatedEvent, value); }
}
private void RaiseTiltingActivatedEvent()
{
RoutedEventArgs newEventArgs =
new RoutedEventArgs(MyControl.TiltingActivatedEvent, this);
RaiseEvent(newEventArgs);
}
Then, I'm calling RaiseTiltingActivatedEvent() in one method called by my IsTilting DependencyProperty Callback when its new value is true, and RaiseTiltingDisabledEvent() when its new value is false.
Note : IsTilting value is changed to either true of false upon Ellipse "Click", and the two events are fired accordingly. But there's a problem : it's not the Ellipse that fires the Events, but the UserControl itself.
Anyway, I tried to replace the <EventTrigger RoutedEvent="UIElement.MouseEnter"> with the followings :
Attempt one :
<EventTrigger RoutedEvent="
{Binding ic:MyControl.TiltingActivated,
ElementName=ThisUserControl}">
.. and I get :
"System.Windows.Markup.XamlParseException: (...)"
"A 'Binding' can only be set on a DependencyProperty of a DependencyObject."
I'm assuming I cannot bind to an Event ?
Attempt two :
<EventTrigger RoutedEvent="ic:MyControl.TiltingActivated">
.. and I get :
"System.NotSupportedException:"
"cannot convert RoutedEventConverter from system.string"
I'm assuming the RoutedEvent name cannot be resolved ? Anyway, this approach make me drift far from my initial goal : Trigger a DoubleAnimation when a custom Property changes (because in more complex scenarios, wouldn't it be easier to trigger different animations and call specific methods, all in CodeBehind when we can have dozens of different values, than creating lengthy and tricky XAML things ? Best would be learning how to do both of course. I'm eager to know)
3) Then I came across this article : Beginner's WPF Animation Tutorial.
A Code Behind Animation Creation. That's the thing I wanted to learn after knowing how to do it in XAML. Anyway, let's have a try.
a) Create two Animation Properties (private), one for tilting animate and another for tilting animate back.
private DoubleAnimation p_TiltingPlay = null;
private DoubleAnimation TiltingPlay
{
get {
if (p_TiltingPlay == null) {
p_TiltingPlay =
new DoubleAnimation(
0.0, 45.0, new Duration(TimeSpan.FromSeconds(0.2)));
}
return p_TiltingPlay;
}
}
// Similar thing for TiltingReverse Property...
b) Subscribe to the two events then set the Angle Animation of our RotateTransform live at runtime in code behind :
private void MyControl_TiltingActivated(object source, EventArgs e)
{
TiltRotate.BeginAnimation(
RotateTransform.AngleProperty, TiltingPlay);
}
// Same thing for MyControl_TiltingDisabled(...)
// Subscribe to the two events in constructor...
public MyControl()
{
InitializeComponent();
this.TiltingActivated +=
new RoutedEventHandler(MyControl_TiltingActivated);
this.TiltingDisabled +=
new RoutedEventHandler(MyControl_TiltingDisabled);
}
Basically, when I "click" (MouseButtonLeftDown + Up) on the Ellipse :
Mouse hit spot is resolved
if within the Ellipse area, change DP IsTilting to not IsTilting.
IsTilting then fires either TiltingActivated or TiltingDisabled.
Both are captured, then the related tilting animation (private properties) is activated on the named <RotateTransform ..> of the Grid.
And it works !!!
I said it would be very easy in code behind ! (lengthy code .. yes, but it works) Hopefully, with snippets templates, it's not that boring.
But I still don't know how to do it in XAML. :/
4) Since my custom events seems to be out of scope in the XAML side, what about <Style> ? Usually, binding in a Style is like breathing. But honestly, I don't know where to begin.
the animation target is the Angle Property of a <RotateTransform /> applied to a Grid.
the binded Dep. Property IsTilting is a custom DP of MyControl, not UserControl.
and one Ellipse drives the updating of the DP.
let's try something like <RotateTransform.Style>
<RotateTransform ...>
<RotateTransform.st...>
</RotateTransform>
<!-- such thing does not exists -->
or RotateTransform.Triggers ? ... doesn't exist either.
UPDATE :
This approach works by declaring the Style in the Grid to animate, as explained in Clemens's answer. To resolve the custom
UserControl Property binding, I just had to use
RelativeSource={RelativeSource AncestorType=UserControl}}. And to
"target" the Angle Property of the RotateTransform, I just had to use
RenderTransform.Angle.
What else ?
I often see samples that sets the DataContext to something like "self". I don't really understand what's a DataContext, but I'm assuming it makes all Path resolving point to the declared Class by default, for Bindings. I already used that in one UserControl which solved my issue, but I didn't dig deeper to understand the how and why. Perhaps this could help resolve capturing custom Events in code behind directly from the XAML side ?
One XAML mostly way I'm nearly sure will work is :
to create a custom UserControl for that Ellipse, say, EllipseButton, with its own Events and Properties
then, embed that in MyControl UserControl.
Capture the TiltingActivated Event of the EllipseButton to trigger the DoubleAnimation in a Storyboard of the EllipseButton, just like it could be done for the Click event of a Button.
That would work fine, but I find it hacky to create and embed another control just to be able to access the appropriate custom event. MyControl is not a SuperWonderfulMegaTop project that would require such surgery. I'm sure I'm missing something soooooooo obvious; can't believe something that simple outside the WPF world can't be even simplier in WPF.
Anyway, such cross-connections are highly subject to memory leaks (perhaps not the case here, but I try to avoid that whenever possible...)
Perhaps defining <Grid.Style> or alike would do the trick ... but I don't know how. I only know how to use <Setter>. I don't know how to create EventTriggers in a Style declaration. UPDATE : Explained by Clemens's answer.
This SO question (Fire trigger in UserControl based on DependencyProperty) suggests to create a Style in UserControl.Resources. Tried the following... It doesn't work (and there is no animation there anyway - I don't know how to declare animation in Style yet)
.
<Style TargetType="RotateTransform">
<Style.Triggers>
<DataTrigger
Binding="{Binding IsTilting, ElementName=ThisUserControl}" Value="True">
<Setter Property="Angle" Value="45.0" />
</DataTrigger>
</Style.Triggers>
</Style>
This SO question (Binding on RotateTransform Angle in DataTemplate not taking effect) has a lot of unknown knowledge to me to be understandable. However, assuming the suggested workaround works, I don't see anywhere something looking like an animation. Just a binding to a value that is not animated. I don't think the Angle animates itself magically.
In Code Behind like the working code above, I could create another DependencyProperty called GridAngle (double), then bind the Angle Property of RotateTransform to that new DP, then animate that DP directly ??? Worth a try, but at a later time : I'm tired.
Just found that my Registered Events are of Bubble Strategy. This would matter if the Event is to be captured by some parent containers, but I want to handle everything directly inside the UserControl, not like on this SO question. However, Tunneling strategy - that I don't understand yet - may play a role : would Tunneling allows my Ellipse to capture the Events of my UserControl ? Have to read the documentation again and again because it's still very obscure to me... What bugs me now is that I am still unable to use my custom events in this UserControl :/
What about a CommandBinding ? That seems very interresting, but it's a whole different chapter to learn. It seems to involve a lot of code behind, and since I already have a working code behind (which looks more readable to me...)
In this SO question (WPF Data Triggers and Story Boards), the accepted answer seems to only work if I'm animating a property of an UI Element that can have a UIElement.Style definition. RotateTransform doesn't have such ability.
Another answer suggest the use of ContentControl, ControlTemplate... Just like CommandBinding above, I haven't dig deep enough to understand how I could adapt that to my UserControl.
However, those answers seems the ones that mostly fit my needs, expecially that ContentControl way. I'll have some tries at a later time, and see if it solves the XAML mostly way of implementing the desired behaviour. :)
And last, this SO question (EventTrigger bind to event from DataContext) suggest the use of Blend/Interactivity. The approach looks nice, but I don't have Blend SDK and not really willing to unless I absolutely have to... Again : another whole Chapter to eat... :/
Side note :
As you would have guessed, I'm a beginner in WPF/XAML (I know it's not an excuse) which I started to learn a few weeks ago. I'm kind of "the whole stuff would be very easy to do in WinForms right now..." but perhaps you could help me figure out how easy it would be to achieve it in WPF :)
I've searched alot (I know it's not an excuse either) but I have no luck for this time. - Okay, I've just read three dozens of articles, code projects and SO topics, and the MSDN documentation about triggers, animations, routed events.. just seems to polish the surface without digging deep in the core (seems like MS think inheriting from Button is the way to solve almost anything...)
Long question, short answer. Use Visual States:
<UserControl ...>
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup>
<VisualState x:Name="TiltedState">
<Storyboard>
<DoubleAnimation
Storyboard.TargetName="TiltingGrid"
Storyboard.TargetProperty="RenderTransform.Angle"
To="45" Duration="0:0:0.2"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Grid x:Name="TiltingGrid" RenderTransformOrigin="0.3, 0.5">
<Grid.RenderTransform>
<RotateTransform/>
</Grid.RenderTransform>
...
</Grid>
</Grid>
</UserControl>
Whenever an appropriate condition is met, call
VisualStateManager.GoToState(this, "TiltedState", true);
in the UserControl's code behind. This may of course also be called in the PropertyChangedCallback of a dependency property.
Without using Visual States, you might create a Style for your TiltingGrid which uses a DataTrigger with a Binding to your UserControl's IsTilted property:
<Grid x:Name="TiltingGrid" RenderTransformOrigin="0.3, 0.5">
<Grid.Style>
<Style TargetType="Grid">
<Style.Triggers>
<DataTrigger Binding="{Binding IsTilted,
RelativeSource={RelativeSource AncestorType=UserControl}}"
Value="True">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetProperty="RenderTransform.Angle"
To="45" Duration="0:0:0.2"/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
<DataTrigger.ExitActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetProperty="RenderTransform.Angle"
To="0" Duration="0:0:0.2"/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.ExitActions>
</DataTrigger>
</Style.Triggers>
</Style>
</Grid.Style>
<Grid.RenderTransform>
<RotateTransform/>
</Grid.RenderTransform>
...
</Grid>
I am developing a Windows 8 Store App. I have created the following user control:
<UserControl
x:Class="RTV_W8.AnimatedImage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:RTV_W8"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<UserControl.Resources>
<!-- Animates the rectangle's opacity. -->
<Storyboard x:Name="ContainerGridStoryboard">
<DoubleAnimation
Storyboard.TargetName="MainGrid"
Storyboard.TargetProperty="Opacity"
From="0" To="1" Duration="0:0:5"
AutoReverse="False">
</DoubleAnimation>
</Storyboard>
</UserControl.Resources>
<Grid x:Name="MainGrid" CacheMode="BitmapCache">
<Image Stretch="UniformToFill" x:Name="PictureImage"/>
</Grid>
</UserControl>
with the following cs file (only partially displayed here)
public AnimatedImage()
{
this.InitializeComponent();
this.Loaded += AnimatedImage_Loaded;
this.PictureImage.Loaded += PictureImage_Loaded;
}
void AnimatedImage_Loaded(object sender, RoutedEventArgs e)
{
this.ContainerGridStoryboard.Begin();
}
my problem is the storyboard is not launching when the image is loaded. This user control is used inside another usercontrol. I have tried multiple variants trying to make the animation to work, none of them worked. I want the user control to animate it's opacity into view, instead of just pooping up. Although i can see via breakpoints that the ContainerGridStoryboard.Begin(); is executed nothing happens on screen
EDIT: In another usercontrol witch is later used in a datatemplate, if i apply the storyboard on the main grid it works, the usercontrol gets animated. But if i apply it on the second grid (contained in the main grid) or any other element, the animation does not work. That is why i created animatedimage in the first place.
I have just solved the problem. So my usercontrol was inside a couple of grids, inside another usercontrol, inside a datatemplate inside a gridview. The problem was that the main grid witch contained the animatedimage was set with CacheMode="BitmapCache". When i removed that property the images faded in.
When I set the image's source, and embed the UserControl into a page, the image fades in as expected.
I'm using this as a basis to make an animation start using code behind. Based on the contents of the article, I have the following:
<Window.Resources>
<Storyboard x:Key="sbdLabelRotation">
<DoubleAnimation
Storyboard.TargetName="lblHello"
Storyboard.TargetProperty="(TextBlock.RenderTransform).(RotateTransform.Angle)"
From="0"
To="360"
Duration="0:0:0.5"
RepeatBehavior="4x" />
</Storyboard>
</Window.Resources>
I have the following XAML (obviously):
<Label x:Name="lblHello" Content="test" Margin="20"/>
And the code behind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public void AnimateLabelRotation()
{
Storyboard sbdLabelRotation = (Storyboard)FindResource("sbdLabelRotation");
sbdLabelRotation.Begin(this);
}
Which I call from a button click event. The FindResource works and finds the storyboard, but nothing happens. I have managed to get the animation to work on an event trigger, but clearly I'm missing something for the code behind.
This:
<Label x:Name="lblHello" Content="test" Margin="20"/>
and this:
Storyboard.TargetProperty="(TextBlock.RenderTransform).(RotateTransform.Angle)"
are not compatible.
When the animation tries to find the property to animate, it goes to (TextBlock.RenderTransform) and finds null since you didn't declare it (actually it doesn't since you say TextBlock but apply it to Label, more on that later in the answer). Thus it cannot find .(RotateTransform.Angle).
To remedy the issue:
<Label x:Name="lblHello"
Content="test"
Margin="20"
RenderTransformOrigin="0.5,0.5">
<Label.RenderTransform>
<RotateTransform />
</Label.RenderTransform>
</Label>
Notice RenderTransformOrigin setting - this means that the axis of rotation will be in the center of the object (X and Y).
Also, in the animation it should be:
Storyboard.TargetProperty="(Label.RenderTransform).(RotateTransform.Angle)"
There is a link to download the whole project
http://www.galasoft.ch/mydotnet/articles/resources/article-2006102701/GalaSoftLb.Article2006102701.zip
You can study the code and see it running. Sometimes it's more helpful.
Also in your code the part:
sbdLabelRotation.Begin(this);
could be wrong. As you know the this keyword references the class itself, in your case the MainWindow class. You should try without the this keyword.
I have series of buttons with EFFECTS that I'd like simulate clicking in code. The problem is that when I run "someFunction" the effects all trigger at about the same time. I'd like a button to click, then wait for the effect to finish then proceed on to the other buttons. I've tried using Thread.sleep but that doesn't work. Can anyone give me some pointers on how this can be accomplished? Also, is it possible to simulate clicking on multiple buttons at the same time?
Thanks for any help!
someFunction() {
button1.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
//System.Threading.Thread.Sleep(100); doesn't work wait for effect to finish
button2.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
//System.Threading.Thread.Sleep(100); doesn't work
button3.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
//System.Threading.Thread.Sleep(100); doesn't work
button4.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
}
<Button Name="buttonRed" Background="Red" BorderBrush="Black" BorderThickness="1"
Grid.Row="1" Grid.Column="0" Click="buttonRedClick">
<Button.BitmapEffect>
<BlurBitmapEffect x:Name="redBlur" Radius="0" />
</Button.BitmapEffect>
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetName="redBlur"
Storyboard.TargetProperty="Radius"
From="0" To="40" Duration="0:0:0.3"
AutoReverse="True" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Button.Triggers>
</Button>
Try looking at this article by Laurent Bugnion.
From above article:
Note that it is also possible to use the BeginTime property of the
animation object to delay an animation, for example in order to
cascade animations. Another way is to use the Completed event, which
can be set in the XAML code, or in the code-behind. This event implies
that the corresponding method must be present in the code-behind, thus
it is not applicable for pure XAML applications.
Thread.sleep will not work as it defines the sys.val realization, so you can use the following code:
there's the error : <EventTrigger RoutedEvent="Button.Click">
instead it should be: <Event.Trigger.Sleep RoutedEvent="Button.Click">
I have a block arrow and i want to make it blink by just filling it with green. I would like to be able to stop it also. I have a right click menu to start it and stop it.
This is what i have so far. But i cant figure out how to start it. I tried to access it but i got an error:
All objects added to an IDictionary must have a
Key attribute or some other type of key associated with them. Line 11 Position 10.
Here is my xaml code:
<ed:BlockArrow x:Name="ArrowLeft" Fill="Green" HorizontalAlignment="Left" Height="29" Margin="142,0,0,-3" Orientation="Left" Stroke="#FF13FF00" VerticalAlignment="Bottom" Width="39" />
<Window.Resources>
<Storyboard x:Name="Blink" AutoReverse="True" RepeatBehavior="Forever">
<ColorAnimationUsingKeyFrames BeginTime="00:00:00"
Storyboard.TargetName="ArrowLeft"
Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)">
<EasingColorKeyFrame KeyTime="00:00:01" Value="Green"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
So, in the right click menu to start it i have:
private void MenuItemLeft_Click(object sender, RoutedEventArgs e)
{
Storyboard blinkAnimation = TryFindResource("Blink") as Storyboard;
if (blinkAnimation != null)
{
blinkAnimation.Begin();
}
Is there a better way to do this? or what am i doing wrong?
WPF Resources are dictrionaries, hence everything within a Resource must have a key. You can add a key by adding an x:Key attribute. You can then locate your item by indexing into the Resource dictionary directly, Resources["MyKeyName"]
Regarding your method of implementation, it looks fine to me.