Making a WPF Label (or other element) flash using animation - wpf

I have a label that I only make visible based on one of my ViewModel Properties. Here is the XAML:
<Label HorizontalAlignment="Center" VerticalAlignment="Center"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
FontSize="24" Width="200" Height="200" >
<Label.Content >
Option in the money!
</Label.Content>
<Label.Style>
<Style TargetType="{x:Type Label}">
<Setter Property="Visibility" Value="Hidden" />
<Style.Triggers>
<DataTrigger Binding="{Binding OptionInMoney}" Value="True">
<Setter Property="Visibility"
Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</Label.Style>
</Label>
I'm not sure this is the best way, but in any case, I'd also like to have the label flashing. Clearly, I only want it flashing when it is visible. Can someone point me to some example code, or write a quick example to do this? I assume I need some sort of trigger, and an animation. Presumably I also need a trigger when the label is no longer visible so that I stop the animation?
Thanks,
Dave
P.S. Is there a good book or site for all these WPF tricks? Something like the "MFC Answer Book" for those that remember that book.

You could add a Storyboard animation to the Style.Resources and start it in the EnterActions section of the DataTrigger.
A simple DoubleAnimation on the Opacity should work fine
Something like this:
<Label.Style>
<Style TargetType="{x:Type Label}">
<Style.Resources>
<Storyboard x:Key="flashAnimation" >
<DoubleAnimation Storyboard.TargetProperty="Opacity" From="1" To="0" AutoReverse="True" Duration="0:0:0.5" RepeatBehavior="Forever" />
</Storyboard>
</Style.Resources>
<Setter Property="Visibility" Value="Hidden" />
<Style.Triggers>
<DataTrigger Binding="{Binding OptionInMoney}" Value="True">
<Setter Property="Visibility" Value="Visible" />
<DataTrigger.EnterActions>
<BeginStoryboard Name="flash" Storyboard="{StaticResource flashAnimation}" />
</DataTrigger.EnterActions>
<DataTrigger.ExitActions>
<StopStoryboard BeginStoryboardName="flash"/>
</DataTrigger.ExitActions>
</DataTrigger>
</Style.Triggers>
</Style>
</Label.Style>

StoryBoard is certainly the WPF way, but it can be achieved by a simple code also. Here it goes, to make a label background blink:
lblTimer is a Lebel on your form with some text, say, "I AM BLINKING"
This can be applied to any property, as VISIBILITY.
// Create a timer.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
DispatcherTimer timer = new DispatcherTimer();
timer.Tick += timer_Tick;
timer.Interval = new TimeSpan(0, 0, 0, 0, 500);
timer.Start();
}
// The timer's Tick event.
private bool BlinkOn = false;
private void timer_Tick(object sender, EventArgs e)
{
if (BlinkOn)
{
lblTimer.Foreground = Brushes.Black;
lblTimer.Background = Brushes.White;
}
else
{
lblTimer.Foreground = Brushes.White;
lblTimer.Background = Brushes.Black;
}
BlinkOn = !BlinkOn;
}

Try this post. It's called 'Blinking TextBlock' but you can easily swap a TextBox for a Label`.

Related

WPF blinking foreground label [duplicate]

This question already has answers here:
Blinking TextBlock
(3 answers)
Closed 6 years ago.
I'm trying to make the foreground of a label blink. I tried the following code but I get the following exception and I don't know how to solve it.
'System.Windows.Media.Animation.ColorAnimation' animation object cannot be used
to animate property 'Foreground' because it is of incompatible type
'System.Windows.Media.Brush'.
Using this XAML:
<Label Content="{Binding Path=SendingAlert, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
Foreground="Transparent"
HorizontalAlignment="Right">
<Label.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsSending, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
Value="True">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard
Storyboard.TargetProperty="Foreground"
Duration="0:0:0.5">
<ColorAnimation From="Transparent" To="Red" AutoReverse="True" RepeatBehavior="Forever"/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
</DataTrigger>
<!--<DataTrigger Binding="{Binding IsSending}" Value="False">
<Setter Property="Foreground" Value="Transparent"/>
</DataTrigger>-->
</Style.Triggers>
</Style>
</Label.Style>
</Label>
and where
public bool IsSending
{
get { return !CanDoActions; }
}
private string _sendingAlert = "sending";//string.Empty;
public string SendingAlert
{
get { return _sendingAlert; }
set
{
_sendingAlert = value;
OnPropertyChanged(() => SendingAlert);
}
}
Any idea of how to fix this?
The Foreground property is of type Brush, which is different from an object of type Color
You can use a ColorAnimiation to animate an object of type Color, but not of type Brush, so to animate your foreground brush, you need to set the property to the Brush.Color, like this:
Storyboard.TargetProperty="(Foreground).(SolidColorBrush.Color)"

Border Color animation in WPF not working in "real-time"

In WPF app I am trying to animate a border colour change on MouseEnter event of a TextBox.
I searched for a while and followed different tutorials, but everything seems to end up the same way:
When the mouse enters the colour of the border changes to what I have set in the animation "From"
Then nothing happens, no animation at all
When mouse leaves after a period longer then the animation duration the colour changes to what I have set in the animation "To"
If the mouse leaves before the animation duration, the colour of the border changes to some colour "in between"
From this I figured that the animation is happening, but it is not showing it as it animates...
The code is here:
private void txtSpeakMe_MouseEnter(object sender, MouseEventArgs e)
{
ColorAnimation ca = new ColorAnimation();
ca.From = (Color)ColorConverter.ConvertFromString("#0066FF");
ca.To = (Color)ColorConverter.ConvertFromString("#FF0000");
ca.Duration = TimeSpan.FromSeconds(3);
txtSpeakMe.BorderBrush.BeginAnimation(SolidColorBrush.ColorProperty, ca);
}
Any ideas on why it is not showing the animation as it is happening? I tried animation in XAML using MS tutorials, the same effect - it animates but it is not showing the process of animation until mouse leaves...
It may be easier to use a Trigger in the Xaml to perform this animation, Triggers have a EnterActions and ExitActions so you could use the IsMouseOver event to start/stop the animation
Example:
<Border Name="border" BorderThickness="5" Width="200" Height="30">
<TextBox Text="StackOverflow"/>
<Border.Style>
<Style TargetType="Border">
<Setter Property="BorderBrush" Value="#0066FF" />
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Trigger.EnterActions>
<BeginStoryboard HandoffBehavior="SnapshotAndReplace">
<Storyboard>
<ColorAnimation Duration="0:0:3" To="#FF0000" Storyboard.TargetProperty="BorderBrush.Color" />
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard HandoffBehavior="SnapshotAndReplace">
<Storyboard>
<ColorAnimation Duration="0:0:3" To="#0066FF" Storyboard.TargetProperty="BorderBrush.Color" />
</Storyboard>
</BeginStoryboard>
</Trigger.ExitActions>
</Trigger>
</Style.Triggers>
</Style>
</Border.Style>
</Border>
Not sure why TextBox border color is not changing, but you could try this:
<Border Name = "border" BorderThickness="5">
<TextBox MouseEnter="TextBox_MouseEnter" MouseLeave="TextBox_MouseLeave"/>
</Border>
Then try this code on MouseEnter and MaouseLeave:
ColorAnimation ca = new ColorAnimation();
ca.From = (Color)ColorConverter.ConvertFromString("#0066FF");
ca.To = (Color)ColorConverter.ConvertFromString("#FF0000");
ca.Duration = TimeSpan.FromSeconds(3);
Storyboard sb = new Storyboard();
sb.Children.Add(ca);
Storyboard.SetTarget(ca, border);
Storyboard.SetTargetProperty(ca, new PropertyPath("(Border.BorderBrush).(SolidColorBrush.Color)"));
sb.Begin();

Change visibility in EventTrigger

i have style that have rectangle which visibility=hidden.
i want change visibility when mouse enter rectangle.
forasmuch as rectangle doesn't have 'IsMouseOver' property i cant use trigger.
how i can do that? (how can change property with animation)
thanks.
I've looking for an button to write a comment, but i dont found it.
So here comes an answer.
Two things:
How should it possible to set Visisbility of an Element to Visible, if it is hidden? The MouseEnter and MouseLeave events will not be called. So the IsMouseOver Property is always False.
Second thing is, that i'm wondering that the IsMouseOver Property will not work in a trigger (i've tried it, too and....got an exception).
An alternative way is to use EventTriggers on MouseEnter and MouseLeave.
kr
sb
<Rectangle Width="400" Height="400" Fill="Red" Opacity="0">
<Rectangle.Style>
<Style TargetType="Rectangle">
<Style.Triggers>
<EventTrigger RoutedEvent="MouseEnter">
<BeginStoryboard>
<Storyboard TargetProperty="Opacity">
<DoubleAnimation From="0" To="1" Duration="0:0:2" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="MouseLeave">
<BeginStoryboard>
<Storyboard TargetProperty="Opacity">
<DoubleAnimation From="1" To="0" Duration="0:0:2" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Style.Triggers>
</Style>
</Rectangle.Style>
</Rectangle>
Ok, to sum up and add to what others wrote:
The rectangle does have an IsMouseOver property. So it is possible to create a trigger (inside a style) that will work with this property. However, this will not work. Why? Because as far as WPF is concerned, if the element is not visible, the mouse is never over it. In other words, is the element is hidden, IsMouseOver will always be false. Therefore, you can't use it to make the element visible when the user puts the mouse over the place where it should be.
If you are working, with a Rectangle, there is another way: instead of making it not visible, you can change the Rectangle's color to be transparent. That way, it IsMouseOver will work as it should and the following code (as an example) will do what you want:
<Rectangle Width="200" Height="200">
<Rectangle.Style>
<Style TargetType="Rectangle">
<Setter Property="Fill" Value="Transparent"></Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Fill" Value="Yellow"></Setter>
</Trigger>
</Style.Triggers>
</Style>
</Rectangle.Style>
</Rectangle>
Of course, the usage depends on what exactly you want to do, which your question doesn't mention. Another way might be to create another Rectangle with the same dimensions and position as the one you need to hide/show. This new Rectangle would be transparent, but always visible. Then, you can bind your Rectangle's Visibility to this new Rectangle's IsMouseOver.
Visibility has three enumeration, Visible Hidden and Collapsed, therefore you cant directly bind to a bool property or for that matter any property that is not a Visibility property. You can write or find a converter, search on WPF Visibility Converter. Or you can try this:
Use the tag property and bind it to the visibility property, it works fine, it is simple and it is entirely in your style setters and triggers. Of course if your using your tag for something else oh well..
In this case I have two TextBlocks, I want one textblock visible when the mouse enters the other, So when the mouse is over the first, I change its tag property to Visible and bind the second text box Visibility property to the firsts tag property.
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<StackPanel Orientation="Horizontal ">
<TextBlock Name="TextBlockTitle" Text="{Binding Title}">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock }">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Tag" Value="Visible"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="False">
<Setter Property="Tag" Value="Hidden"/>
</Trigger>
</Style.Triggers>
</Style>
</TextBlock.Style></TextBlock>
<TextBlock Name="TextBlockAdd" Text=" + Add New" MouseLeftButtonDown="TextBlockAdd_OnMouseLeftButtonDown">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock }">
<Setter Property="Visibility" Value="{Binding ElementName=TextBlockTitle,Path=Tag}"></Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Visibility" Value="Visible"/>
</Trigger>
<EventTrigger RoutedEvent="MouseLeftButtonDown" ></EventTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>

Datagrid MouseOver and Selected States when using arrow keys

I have a wpf datagrid. I have added styling to show a mouseover color on a row.
What I am trying to achieve is when the mouseover appears, and a user starts using the arrow keys to navigate up and down, the mouseover needs to disappear and only the row that the user used arrow keys to get to, is the highlighted one.
The issue is the mouse cursor has been left on the grid while the user navigates with the arrow keys and the row under the cursor holds the highlight as well as the row the went to using arrows.
Here is my sample xmal:
<DataGrid AutoGenerateColumns="True" Height="277" HorizontalAlignment="Left" Margin="0,311,0,0" Name="dataGrid1"
VerticalAlignment="Top"
Width="478" ItemsSource="{Binding Path=Persons}"
RowHeight="20"
RowHeaderWidth="35" Grid.ColumnSpan="2" >
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<Trigger Property="IsMouseOver"
Value="True">
<Setter Property="Background"
Value="Green" />
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
</DataGrid>
Thanks
You'll need to set some kind of flag when the user hits an Arrow key so that the background only changes if IsMouseOver and IsUsingArrowKeys is false. You might even be able to use the Mouse Visibility as a condition instead of using a flag
I'm not positive the exact syntax, but it should be something like this
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<!-- May need to reference RelativeSource here, not sure -->
<Condition Property="IsMouseOver" Value="False" />
<Condition Binding="{Binding IsUsingArrowKeys}" Value="False" />
</MultiDataTrigger.Conditions>
<Setter Property="Background" Value="Green" />
</MultiDataTrigger>
</Style.Triggers>
I would suggest highlighting the row based on thier focus triggers.
Something like this:
<EventTrigger RoutedEvent="GotFocus">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="dataGrid1" Storyboard.TargetProperty="Background" Duration="0:0:0.1" To="Green"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
<EventTrigger RoutedEvent="LostFocus">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="dataGrid1" Storyboard.TargetProperty="Background" Duration="0:0:0.1" To="White"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
And giving focus to them manually, something like this:
private void Btn_Click(object sender, RoutedEventArgs e)
{
dataGrid1.Focus();
}
So when another row gets focus, the current row loses focus & automatically falls back to non highlighted color background.

Wpf Toolkit Chart Invert Highlighting

How can I highlight other pieces (columns, bars etc.) in a chart created with wpf toolkit. I am using a control template to style my own chart. So far I used a trigger to get a fading effect on the element on which the mouse is residing. I want to invert this; to fade other elements (a popular charting visual gimmick) on to which mouse is not pointing. Following image shows the selected column Faded, I want it to be the other way around.
Just set the default value to faded and use the trigger to bring it up to full opacity. You have done some other styling but here is an example based on the default style:
<Grid>
<Grid.Resources>
<PointCollection x:Key="sampleData">
<Point>1,20</Point>
<Point>2,40</Point>
<Point>3,30</Point>
</PointCollection>
<Style x:Key="dimEffectStyle" TargetType="{x:Type charting:ColumnDataPoint}" BasedOn="{StaticResource {x:Type charting:ColumnDataPoint}}">
<Setter Property="Opacity" Value="0.25"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="Opacity" To="1" Duration="0:0:0.1" />
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="Opacity" To="0.25" Duration="0:0:0.1" />
</Storyboard>
</BeginStoryboard>
</Trigger.ExitActions>
</Trigger>
</Style.Triggers>
</Style>
</Grid.Resources>
<charting:Chart>
<charting:ColumnSeries
Title="A"
ItemsSource="{StaticResource sampleData}"
IndependentValueBinding="{Binding X}"
DependentValueBinding="{Binding Y}"
DataPointStyle="{StaticResource dimEffectStyle}"
/>
</charting:Chart>
</Grid>
Edit:
If you want to change all the other data points except the data point the mouse is over, that is a bit harder and can't be done simply by restyling the controls. But you can create your own series control that has that capability. Here is a chart with an unstyled column series class called MouseNotOverColumnSeries with a new MouseNotOverOpacity property:
<Grid.Resources>
<PointCollection x:Key="sampleData">
<Point>1,20</Point>
<Point>2,40</Point>
<Point>3,30</Point>
</PointCollection>
</Grid.Resources>
<charting:Chart Name="chart1">
<local:MouseNotOverColumnSeries
Title="A"
ItemsSource="{StaticResource sampleData}"
IndependentValueBinding="{Binding X}"
DependentValueBinding="{Binding Y}"
MouseNotOverOpacity="0.5"
/>
</charting:Chart>
Here is the MouseNotOverColumnSeries class:
public class MouseNotOverColumnSeries : ColumnSeries
{
public double MouseNotOverOpacity { get; set; }
protected override void OnDataPointsChanged(IList<DataPoint> newDataPoints, IList<DataPoint> oldDataPoints)
{
base.OnDataPointsChanged(newDataPoints, oldDataPoints);
foreach (var dataPoint in oldDataPoints)
{
dataPoint.MouseEnter -= new MouseEventHandler(dataPoint_MouseEnter);
dataPoint.MouseLeave -= new MouseEventHandler(dataPoint_MouseLeave);
}
foreach (var dataPoint in newDataPoints)
{
dataPoint.MouseEnter += new MouseEventHandler(dataPoint_MouseEnter);
dataPoint.MouseLeave += new MouseEventHandler(dataPoint_MouseLeave);
}
}
void dataPoint_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
{
foreach (var dataPoint in ActiveDataPoints)
if (e.OriginalSource != dataPoint) dataPoint.Opacity = MouseNotOverOpacity;
}
void dataPoint_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
{
foreach (var dataPoint in ActiveDataPoints)
dataPoint.Opacity = 1;
}
}
We just pay attention to when the data points change and register mouse enter/leave handlers that manipulate the opacity of all the other data points that the mouse is not over. This could be expanded to support storyboards, etc.

Resources