Property Value Animation triggered by a custom DependencyProperty in UserControl? - c#

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>

Related

How to set a binding inside a style?

I am fairly new to Xaml.
I am learning UWP(Universal Windows Platform) and I have more buttons and I want to bind their Background property to a property of a ViewModel that will change during some events.
I implemented the INotifyPropertyChanged and everything works ok (the color of the buttons change) when I bind the Background property in the Buttons' declaration in XAML:
<Button Content="0" Grid.Column="0" Grid.Row="5"
Background="{Binding ButtonColor, Source={StaticResource AppViewModel}}" Style="{StaticResource BasicButton}"/>
StaticResource AppViewModel is a resource in App.xaml:
<Application.Resources>
<viewModel:AppViewModel x:Key="AppViewModel" />
</Application.Resources>
I don't know how ok is to declare a ViewModel for App.xaml, but it's a solution I found for having global variables (the variables are held inside the viewModel).
Now back to my question:
As I don't want to bind the Background on every single button, I tried to add it on the style like this:
<Style x:Key="BasicButton" TargetType="Button">
<Setter Property="Background" Value="{Binding ButtonColor, Source={StaticResource AppViewModel}}" />
</Style>
But now when the color variable is changing during running the app, the UI doesn't update anymore.
It seems that binded properties in styles don't respond to changes of variables.
What am I doing wrong?
Thank you for any answers.
After more searching I found a video from Jerry Nixon : http://blog.jerrynixon.com/2013/01/walkthrough-dynamically-skinning-your.html
It seems that because we don't have DynamicResource in uwp / winrt, we have to do a trick:
We renavigate to the same frame. So after we change the property, we have to do something like this:
var frame = Window.Current.Content as Frame;
frame.Navigate(frame.Content.GetType());
frame.GoBack();
It's like invalidating a control in Windows Forms. It's making the UI redraw itself.
I'm not sure if this has side effects, I'll have to dig more. I'll come back if I find any.

StoryBoard object becomes read-only when set by a Style

I have an attached behavior that has a single attached property of type StoryBoard. I want to set this property on every item in a ListView. The XAML looks something like this:
<Grid>
<Grid.Resources>
<Storyboard x:Key="TheAnimation" x:Shared="False">
<DoubleAnimation From="0.0" To="1.0" Duration="0:0:0.20"
Storyboard.TargetProperty="Opacity" />
</Storyboard>
</Grid.Resources>
<ListView>
<ListView.Resources>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="local:MyBehavior.Animation"
Value="{StaticResource TheAnimation}" />
</Style>
</ListView.Resources>
</ListView>
</Grid>
So far so good. Then the code in 'MyBehavior' tries to do this:
private static void AnimationChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var listViewItem = d as ListViewItem;
if (d == null)
return;
var sb = e.NewValue as Storyboard;
if (sb == null)
return;
Storyboard.SetTarget(sb, listViewItem);
sb.Begin();
}
But an InvalidOperationException is thrown on the call to StoryBoard.SetTarget(): "Cannot set a property on object 'System.Windows.Media.Animation.Storyboard' because it is in a read-only state." If I inspect the Storyboard in the debugger, I can see that both its IsSealed and IsFrozen properties are set to true.
By contrast, if I set MyBehavior.Animation directly on the ListView so that I don't need to use a Style, the StoryBoard arrives unsealed and I am able to set the target and run it successfully. But that's not where I want it.
Why is my StoryBoard being sealed, and is there anything I can do to prevent this?
Update: I can solve my problem by adding this right after the null check:
if(sb.IsSealed)
sb = sb.Clone();
But I'm still curious what's going on. Apparently something somewhere (Style? Setter?) is freezing/sealing the object in Setter.Value.
I'm far from an expert in WPF, so I cannot explain the finer details of why this was the choice Microsoft made. But as I understand it, the main issue is that the object that is declared as a resource is likely to be shared with multiple other objects. As such, you are prevented from modifying it.
If you still want to go the resources route, it is possible that you can treat the resource as {DynamicResource...} instead of {StaticResource...} and that might allow you to modify the object that's been used for some other object. As I said, I'm not an expert in WPF and I admit to still being a bit cloudy on the different between DynamicResource and StaticResource, but I have a vague recollection that it addresses this scenario. :)
I've done some research on this, and think I've worked out most of what's going on. The short answer is that this behavior is by design. The MSDN Styling and Templating page for .net 4.0 says flat-out that "once a style has been applied, it is sealed and cannot be changed." Comments with Style.IsSealed back this up. But that's the Style itself; I'm dealing with an object contained in a Style's Setter's Value. Well, Style.Seal seals all its Setters, and Setter.Seal seals its Value. With that info in hand (head), none of what happened here is particularly shocking. But there's still no explanation for why all this sealing is being done in the first place. There are claims here and here that it is related to thread safety. That seems reasonable, but I would speculate further that, if all objects that consume a particular Style share a single Style object (and I don't know if that's the case or not), the sealing might be done for the simple reason that you don't want one consumer modifying the Style and accidentally changing everyone else.
All this seems to mean that there is no general solution to the problem, and it will need to be solved on a case-by-case basis. In my case, the solution was simply to clone the Storyboard and then operate on that clone.

Architecting...a slideshow

I know this sounds silly and I could use some out-of-the-box solution, but I really want to build my own simple image slideshow. I've been doing application development in Silverlight/WPF for some time, but for whatever reason I can't wrap my head around this.
I have an observable collection of SlideshowItem
Each SlideshowItem has Source which indicates where the image for it is located
I show a translucent box for each SlideshowItem (horizontal list using a stackpanel) and when you click, you should transition to that slide
So here's my problem: If I have that list with a stackpanel template, and under the list is an image taking up the size of the canvas, I can bind the context of the image to the selected SlideshowItem. That's all well and good. But when I click/change the selected index of the list, I want to do a crossfade or slide between two images.
How should I represent this in Silverlight? Should I actually have a scroll panel or something with all the images and then change between them? Or is it sufficient to use a single image control? Can I do this with states, or do I need to explicitly run a storyboard? Any samples would be appreciated.
You can use the TransitioningContentControl from the Silverlight Toolkit, however if you want to roll your own you will need two content controls and swap out the "Active" one on SelectionChanged events. You also can fire your storyboards here.
ContentControl _active;
private void LB_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_active == Content1)
{
_active = Content2;
Content2Active.Begin();
} else
{
_active = Content1;
Content1Active.Begin();
}
_active.Content = LB.SelectedItem;
}
And the Xaml looks something like this. I just use strings and text, but this approach should work reasonable well for images too:
<Grid x:Name="LayoutRoot" Background="White" MaxHeight="200">
<Grid.Resources>
<Storyboard x:Name="Content1Active">
<DoubleAnimation From="0" To="1" Storyboard.TargetName="Content1" Storyboard.TargetProperty="(UIElement.Opacity)" />
<DoubleAnimation To="0" Storyboard.TargetName="Content2" Storyboard.TargetProperty="(UIElement.Opacity)" />
</Storyboard>
<Storyboard x:Name="Content2Active">
<DoubleAnimation From="0" To="1" Storyboard.TargetName="Content2" Storyboard.TargetProperty="(UIElement.Opacity)" />
<DoubleAnimation To="0" Storyboard.TargetName="Content1" Storyboard.TargetProperty="(UIElement.Opacity)" />
</Storyboard>
</Grid.Resources>
<StackPanel>
<ListBox x:Name="LB" SelectionChanged="LB_SelectionChanged" xmlns:sys="clr-namespace:System;assembly=mscorlib">
<sys:String>Red</sys:String>
<sys:String>Green</sys:String>
<sys:String>Blue</sys:String>
</ListBox>
<Grid>
<ContentControl x:Name="Content1" FontSize="40" Foreground="{Binding Content, RelativeSource={RelativeSource Self}}">
</ContentControl>
<ContentControl x:Name="Content2" FontSize="40" Foreground="{Binding Content, RelativeSource={RelativeSource Self}}">
</ContentControl>
</Grid>
</StackPanel>
</Grid>
Definitely you don't need the entire Image collection displayed in a scrollviewer/stackpanel. You can implement this in many different ways. I can explain a simple idea of Using one Image : As you said , define a SelectedSlide property in your ViewModel and bind that to an Image control ( Preferably a ContentControl with Image as its part of the ContentTemplate, so that you can have descriptions and other items in the same). This solution can give you the opportunity to add some storyboards so that if you increase your SelectedIndex(Another VM property) fire a storyboard to do a 'Left Move' animation and if you decrease do a 'Right Move' animation makes user feels like slides are coming from one side and going the other way. You can do pretty good UX on that set of storyboards.
Update (Idea 2) : Yes if we need the notion of the previous one leaving the view when new one coming in, we can architect it by using two ContentControls wrapped inside a CustomControl ( lets call it as SlideShowControl). SlideShowControl will have its mechanism to properly set DataContext of the two ContentControl based on the selectedIndex position. I have successfully made this control in one of my projects, the logic here is to switch the ContentControls through a storyboard so that we can have many different effects by swapping the storyboard. Suppose you move from Index 1 to 2, ContentControlA will animate to left, and B will come in to the View, and based on your next click ControlA will go sit either left or right of the View, and comes with new DataContext of the selected View.

How to set an event function via a style?

I have several GUI control elements of which some are supposed to generate the same action (code-behind function call) on mouse interaction (MouseEnter, MouseLeave).
[edit] I am performing some non style related functionality in my event handlers.
Right now I'm using event attributes in each control:
<Button Name="Button" Content="Button 1"
MouseEnter="GeneralMouseEnter" MouseLeave="GeneralMouseLeave"
PreviewMouseDown="Button1_PreviewMouseDown" PreviewMouseUp="Button1_PreviewMouseUp" />
<Button Name="NotInteractingButton" Content="Button 2"
/><!-- this button has no MouseOver-effects -->
<ToggleButton Content="ToggleButton"
MouseEnter="GeneralMouseEnter" MouseLeave="GeneralMouseLeave" />
<!-- needs to use IsMouseDirectlyOver on the slider knob... -->
<Slider Name="HorizontalSlider"
MouseEnter="GeneralMouseEnter" MouseLeave="GeneralMouseLeave"
ValueChanged="Slider_ValueChanged" />
<Slider Name="VerticalSlider" Orientation="Vertical"
MouseEnter="GeneralMouseEnter" MouseLeave="GeneralMouseLeave"
ValueChanged="Slider_ValueChanged" />
Since many controls in this example are calling the same two functions "GeneralMouseEnter" and "GeneralMouseLeave", I'd like to be able to define a style or something similar to encapsulate that behavior.
[edit - clarification]
This is supposed to become a kind of plugin later on.
(Include code and XAML files to any GUI program and set a style on each interactive control element...)
From what I found on the web, I can use EventTriggers like in this example:
<Style.Triggers>
<EventTrigger RoutedEvent="Click">
<EventTrigger.Actions>
<BeginAction TargetName="SomeAction" />
</EventTrigger.Actions>
</EventTrigger>
</Style.Triggers>
I don't know though if and how to call functions within an action.
Is it possible to get this functionality by creating a style with action + trigger to be applied to each control? How to do that?
How do I assign multiple styles (for multiple interaction events) to one control?
Is there maybe even a cleaner way to achieve this behavior?
[edit]
What if I want to, let's say, have mouse interaction on all sliders in my GUI?
Martin,
you can assign an event handler directly from a style using an EventSetter:
<Style TargetType="{x:Type Button}">
<EventSetter Event="Click" Handler="SomeAction"/>
</Style>
#ColinE:
I am not sure that using a style to perform event wire-up is a good idea. Styles, by definition, define the visual appearance of controls.
Unfortunately, this seems to be a common and widespread misconception about WPF styles: Although their name suggests they are, like what you say, merely meant to define the visual appearance, they are actually much more: It is helpful to view styles more generally as a shortcut for assigning a set of properties to a control.

How do you add an Event Trigger to a data template for a business object?

I have a custom class named BlinkingLight.
I also have a static ObservableCollection BlinkingLightCollection.
In the UI, I have a ListBox that is bound to BlinkingLightCollection.
In my ListBox I want to essentially display each BlinkingLight object as a custom control that looks like box with an LED light that has an animation that makes the LED look like it just flashed on for a second then goes back to normal.
My BlinkingLight class has third party "LED" object that raises an event called 'Flash'.
I am looking for ideas or solutions to get this to work!
My failed attempt:
I created a custom control (BlinkingLightControl) that can bind to the data of my BlinkingLight class when a BlinkingLight is the DataContext of my custom control.
I created a DataTemplate for my ListBox:
<Window.Resources>
<DataTemplate x:Key="blinkingLightItemTemplate" >
<local:BlinkingLightControl />
</DataTemplate>
</Window.Resources>
<ListBox ItemsSource={Binding Source={x:Static local:Data.BlinkingLightCollection}}
ItemTemplate="{StaticResource blinkingLightItemTemplate}" />
Note: I can just put the xaml for my custom control into the datatemplate instead having a completely different control if that makes things easier.
Now I want to have an EventTrigger in my BlinkingLightControl (or DataTemplate) who's RoutedEvent is the LED.Flash event. Unfortunately I can't seem to figure this part out. I've tried to create a RoutedEvent in my BlinkingLight class and just raise it whenever I handle the LED.Flash event. However my class is not a UIElement or ContentElement, and per MSDN: MSND Link
"The routed event owner can be any class, but routed events must be raised by and handled by UIElement or ContentElement derived classes in order to be useful. For more information about custom events, see How to: Create a Custom Routed Event."
Any help would be greatly appreciated!!
Thanks,
Scott
In this case, the best way is to use WPF Commanding and create a "BlinkTheLights" RoutedCommand - your BlinkingLightControl will handle the BlinkTheLights command, and respond by starting a StoryBoard which does the light blink.
I was able to come up with a solution that has worked quite well:
Since my DataTemplate simply contains a custom UserControl (which binds to the DataContext to get its data from the business object)... I placed my custom RoutedEvent in the UserControl. Then in my UserControl's loaded event, I cast the DataContext as my business object to get access to the business object's property that has the event and hook it up to an event handler. (in my example I cast the DataContext as a BlinkingLight object, then I can get access to its Led property's Flash event and hook it up to a custom event handler).
Note: The LED object must be a property, not just a field in the BlinkingLight object for it to work.
Then the event handler can raise the UserControl's custom Routed Event (FlashGreenEvent). Below is the back end code that now supplements the code in the OP (I've stripped out any other irrelevant code).
public partial class BlinkingLightControl : UserControl
{
public static readonly RoutedEvent FlashGreenEvent = EventManager.RegisterRoutedEvent("FlashGreen", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(BlinkingLightControl));
public event RoutedEventHandler FlashGreen
{
add { AddHandler(FlashGreenEvent, value); }
remove { RemoveHandler(FlashGreenEvent, value); }
}
private void BlinkingLightControl_Loaded(object sender, RoutedEventArgs e)
{
BlinkingLight blinkingLight = (BlinkingLight)this.DataContext;
blinkingLight.Led.Flash += LED_Flash;
}
protected delegate void LED_FlashCallback(ThirdParty.LED sender);
public void LED_Flash(ThirdParty.LED sender)
{
if (this.Dispatcher.CheckAccess())
{
// Raise the Flash Green Event;
RaiseEvent(new RoutedEventArgs(BlinkingLightControl.FlashGreenEvent));
}
else
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new LED_FlashCallback(LED_Flash), sender);
}
}
If you're making a custom control you could always set the trigger outside of the control template.
something like:
<Style TargetType="{x:Type local:MyControl}">
<!-- fade in the control with an animation -->
<Style.Triggers>
<EventTrigger RoutedEvent="Control.Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation To="1" Duration="0:0:1" Storyboard.TargetProperty="Opacity"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Style.Triggers>
<!-- Make sure the opacity starts at 0 -->
<Setter Property="Opacity" Value="0"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MyControl}">
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

Categories

Resources