I am trying to achieve a simple label scroller(found the idea here: Scroller StackOverflow. I have a label, which I want to animate with help of DoubleAnimation class like this:
In constructor I implement event for Loaded:
public Web()
{
InitializeComponent();
SetDefaultBrowser();
SetDefaultWebsite();
//TextBlockSong.Text = GetSongName(GetBrowserName(), GetWebsiteName());
Loaded += Window1_Loaded;
}
Event:
void Window1_Loaded(object sender, RoutedEventArgs e)
{
DoubleAnimation doubleAnimation = new DoubleAnimation();
doubleAnimation.From = -LabelNameSong.ActualWidth;
doubleAnimation.To = canMain.ActualWidth;
doubleAnimation.RepeatBehavior = RepeatBehavior.Forever;
doubleAnimation.Duration = new Duration(TimeSpan.Parse("0:0:10"));
LabelNameSong.BeginAnimation(Canvas.RightProperty, doubleAnimation);
}
Everything works until I update my LabelNameSong content. The LabelNameSong width stays the same as before, and my animation doesn't work properly from the start anymore(with updated text).
I update my LabelNameSong with ListBox_SelectionChanged event:
private void ListBoxWebsite_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
double k = LabelNameSong.Width;
double z = LabelNameSong.ActualWidth;
LabelWebsiteName.Content = "Now on " + GetWebsiteName();
LabelNameSong.Content = GetSongName(GetBrowserName(), GetWebsiteName());
k = LabelNameSong.Width;
z = LabelNameSong.ActualWidth;
}
I used those to measure width, and found out that it doesn't update the width of LabelNameSong. I am new here, don't even know if it should.
This is my xaml:
<Canvas Background="White" Margin="0,182,58,0" >
<Canvas ClipToBounds="True" Name="canMain" Height="80" Width="346" >
<Label FontSize="25" Foreground="#666666" Name="LabelNameSong" Canvas.Top="27" Height="30" Width="Auto" Content="This is very long text, I am testing it!" FontFamily="Calibri Light"/>
</Canvas>
</Canvas>
So my question is, what could I do to update the width of my LabelNameSong, and how should I re-call Window1_Loaded event so new instance of DoubleAnimation would work with updated ActualWidth?
doubleAnimation.From = -LabelNameSong.ActualWidth;
doubleAnimation.To = canMain.ActualWidth;
Thank you.
You can just wrap the Animation logic into a method and call from Loaded event and any other event you need
private void CreateAnimation()
{
DoubleAnimation doubleAnimation = new DoubleAnimation();
doubleAnimation.From = -LabelNameSong.ActualWidth;
doubleAnimation.To = canMain.ActualWidth;
doubleAnimation.RepeatBehavior = RepeatBehavior.Forever;
doubleAnimation.Duration = new Duration(TimeSpan.Parse("0:0:10"));
LabelNameSong.BeginAnimation(Canvas.RightProperty, doubleAnimation);
}
void Window1_Loaded(object sender, RoutedEventArgs e)
{
CreateAnimation();
}
private void LabelNameSong_SizeChanged(object sender, RoutedEventArgs e)
{
CreateAnimation();
}
But you can probably do it all in Xaml using Triggers and get rid of all that code behind.
In the example below the animation will start on Load and restart when the Size changes
Example:
<Label x:Name="LabelNameSong" Content="Hello" >
<Label.Resources>
<Storyboard x:Key="scroll">
<DoubleAnimation To="{Binding ActualWidth, ElementName=LabelNameSong}" Duration="00:00:10"
Storyboard.TargetProperty="(Canvas.Right)"
Storyboard.TargetName="LabelNameSong"
RepeatBehavior="Forever"/>
</Storyboard>
</Label.Resources>
<Label.Triggers>
<EventTrigger RoutedEvent="Label.Loaded">
<BeginStoryboard Storyboard="{StaticResource scroll}" />
</EventTrigger>
<EventTrigger RoutedEvent="Label.SizeChanged">
<BeginStoryboard Storyboard="{StaticResource scroll}" />
</EventTrigger>
</Label.Triggers>
</Label>
Related
Initially I did it directly on nInput and everything worked.
Then I tried to move it to a cloned object (cloneInputForAnimation) but I get this error:
System.InvalidOperationException: The name 'TextBoxAnim' could not be
found in the namespace of 'System.Windows.Controls.TextBox'
XAML:
<TextBox x:Name="nInput" MaxLength="17" PreviewTextInput="numberValidationTextBox" Grid.Column="0"
Height="80" Width="240"
Foreground="White" Background="#202020"
HorizontalAlignment="Left" BorderThickness="0"
HorizontalContentAlignment="Center" VerticalContentAlignment="Center"
FontSize="25">
<TextBox.RenderTransform>
<TranslateTransform x:Name="TextBoxAnim" />
</TextBox.RenderTransform>
<TextBox.Resources>
<Storyboard x:Key="myStoryboardY" x:Name="myStoryboardY">
<DoubleAnimation
Storyboard.TargetName="TextBoxAnim"
x:Name="myDoubleAnimationY"
Storyboard.TargetProperty="Y"
Duration="0:0:0.8"
/>
</Storyboard>
<Storyboard x:Key="myStoryboardX" x:Name="myStoryboardX">
<DoubleAnimation
Storyboard.TargetName="TextBoxAnim"
x:Name="myDoubleAnimationX"
Storyboard.TargetProperty="X"
Duration="0:0:0.8"
/>
</Storyboard>
<Storyboard x:Key="myStoryboardWidth" x:Name="myStoryboardWidth">
<DoubleAnimation
Storyboard.TargetName="nInput"
x:Name="myDoubleAnimationWidth"
Storyboard.TargetProperty="(TextBox.Width)"
Duration="0:0:0.8"
/>
</Storyboard>
<Storyboard x:Key="myStoryboardHeight" x:Name="myStoryboardHeight">
<DoubleAnimation
Storyboard.TargetName="nInput"
x:Name="myDoubleAnimationHeight"
Storyboard.TargetProperty="(TextBox.Height)"
Duration="0:0:0.8"
/>
</Storyboard>
</TextBox.Resources>
</TextBox>
C#:
//I clone the input box to perform the animation
TextBox cloneInputForAnimation = CloneXaml(nInput);
UserInteraction.Children.Add(cloneInputForAnimation);
//Removing text from the realInput
nInput.Text = "";
//nInput.IsEnabled = false;
//Creating a new object which is the one that will remain after the animation
TextBox targetInput = CloneXaml(cloneInputForAnimation);
targetInput.Visibility = Visibility.Hidden;
targetInput.Width = Double.NaN;
targetInput.Height = 50;
nList.Children.Add(targetInput);
//Obtaining the destination point
Point targetPosition = targetInput.TransformToAncestor(rootView).Transform(new Point(0, 0));
//Obtaining the current point
Point currentPos = cloneInputForAnimation.TransformToAncestor(rootView).Transform(new Point(0, 0));
//Calculating the translation to do to reach targetPosition
Vector translateToDo = targetPosition - currentPos;
//Obtaining storyboard and anim for x, y, width, height of cloneInputForAnimation (I can't use x:Name because is an element created programmatically)
Storyboard myStoryY = cloneInputForAnimation.Resources["myStoryboardY"] as Storyboard;
Storyboard myStoryX = cloneInputForAnimation.Resources["myStoryboardX"] as Storyboard;
Storyboard myStoryHeight = cloneInputForAnimation.Resources["myStoryboardHeight"] as Storyboard;
Storyboard myStoryWidth = cloneInputForAnimation.Resources["myStoryboardWidth"] as Storyboard;
DoubleAnimation myAnimY = myStoryY.Children[0] as DoubleAnimation;
DoubleAnimation myAnimX = myStoryX.Children[0] as DoubleAnimation;
DoubleAnimation myAnimHeight = myStoryHeight.Children[0] as DoubleAnimation;
DoubleAnimation myAnimWidth = myStoryWidth.Children[0] as DoubleAnimation;
myAnimY.To = translateToDo.Y;
myAnimX.To = translateToDo.X;
myAnimHeight.To = targetInput.ActualHeight;
myAnimWidth.To = targetInput.ActualWidth;
cloneInputForAnimation.BeginStoryboard(myStoryY);
cloneInputForAnimation.BeginStoryboard(myStoryX);
cloneInputForAnimation.BeginStoryboard(myStoryHeight);
cloneInputForAnimation.BeginStoryboard(myStoryWidth);
C# CloneXaml:
public static T CloneXaml<T>(T source)
{
string xaml = XamlWriter.Save(source);
StringReader sr = new StringReader(xaml);
XmlReader xr = XmlReader.Create(sr);
return (T)XamlReader.Load(xr);
}
Sorry but these are my first steps with WPF so the code will probably have a lot of problems.
Okay, as I imagined I was using a completely wrong approach.
This is the working version I have arrived at.
XAML:
<TextBox x:Name="nInput" MaxLength="17" PreviewTextInput="numberValidationTextBox" Grid.Column="0"
Height="80" Width="240"
Foreground="White" Background="#202020"
HorizontalAlignment="Left" BorderThickness="0"
HorizontalContentAlignment="Center" VerticalContentAlignment="Center"
FontSize="25">
<TextBox.Resources>
<Style TargetType="{x:Type Border}">
<Setter Property="CornerRadius" Value="12" />
</Style>
</TextBox.Resources>
</TextBox>
C#:
Duration animDuration = new Duration(new TimeSpan(0, 0 ,0, 0,800));
//I clone the input box to perform the animation
TextBox cloneInputForAnimation = CloneXaml(nInput);
UserInteraction.Children.Add(cloneInputForAnimation);
//Removing text from the realInput
nInput.Text = "";
//nInput.IsEnabled = false;
//Creating a new object wich is the one that will remain after the animation
TextBox targetInput = CloneXaml(cloneInputForAnimation);
targetInput.Visibility = Visibility.Hidden;
targetInput.Width = double.NaN;
targetInput.Height = 50;
nList.Children.Add(targetInput);
//Obtaining the destination point
Point targetPosition = targetInput.TransformToAncestor(rootView).Transform(new Point(0, 0));
//Obtaining the current point
Point currentPos = cloneInputForAnimation.TransformToAncestor(rootView).Transform(new Point(0, 0));
//Calculating the translation to do to reach targetPosition
Vector translateToDo = targetPosition - currentPos;
TranslateTransform myTranslateTransform = new TranslateTransform();
cloneInputForAnimation.RenderTransform = myTranslateTransform;
DoubleAnimation myAnimX = new DoubleAnimation {
Duration = animDuration,
To = translateToDo.X
};
DoubleAnimation myAnimY = new DoubleAnimation {
Duration = animDuration,
To = translateToDo.Y
};
DoubleAnimation myAnimHeight = new DoubleAnimation {
Duration = animDuration,
To = 50,
};
DoubleAnimation myAnimWidth = new DoubleAnimation {
Duration = animDuration,
To = 50,
};
myTranslateTransform.BeginAnimation(TranslateTransform.YProperty, myAnimY);
myTranslateTransform.BeginAnimation(TranslateTransform.XProperty, myAnimX);
cloneInputForAnimation.BeginAnimation(TextBox.WidthProperty, myAnimWidth);
cloneInputForAnimation.BeginAnimation(TextBox.HeightProperty, myAnimHeight);
C# CloneXaml has not been modified
I want to make a bubble window that GRADUALLY appears and vanishes after having displayed a message. I want its position to be near the tray and in the constructor I use for that:
var screenSize = System.Windows.SystemParameters.WorkArea;
this.Left = screenSize.Right - this.Width;
this.Top = screenSize.Bottom - this.Height;
this has worked properly other times but now it doesn't.
Strangely enough also the opacity doesn't change. So to put it in a nutshell the window appear all of a sudden with no gradual transition at the center of the screen instead than near the tray.
This is the code:
public BubbleWindow(string strMessage, double milliseconds)
{
InitializeComponent();
btYes.Content = strMessage;
var screenSize = System.Windows.SystemParameters.WorkArea;
this.Left = screenSize.Right - this.Width;
this.Top = screenSize.Bottom - this.Height;
int interval = (int)(milliseconds / 25);
for (double iii = 0; iii <= 1; iii += .1)
{
Thread.Sleep(interval);
this.Opacity = iii;
Dispatcher.Invoke((Action)(() => { }), DispatcherPriority.Render);
this.UpdateLayout();
}
this.Opacity = 1;
}
Thanks for any help
You can use this code in your XAML
<EventTrigger RoutedEvent="Rectangle.Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetName="MyRectangle"
Storyboard.TargetProperty="Opacity"
From="1.0" To="0.0" Duration="0:0:5" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
This is pure XAML way
Or you can use
<Storyboard x:Name="anim">
<DoubleAnimation
Storyboard.TargetName="MyRectangle"
Storyboard.TargetProperty="Opacity"
From="1.0" To="0.0" Duration="0:0:5" />
</Storyboard>
and then start the animation from c#
you can take reference from here
As for the position problem I had put the WindowPosition=CenterScreen in my xaml code. That overrode the .left and .top command.
For the sake of completeness this is the complete Fade IN - wait - Fade out cycle:
private Storyboard myStoryboard;
public MainWindow()
{
InitializeComponent();
DoubleAnimation fadeInAnimation = new DoubleAnimation() { From = 0.0, To = 1.0, Duration = new Duration(TimeSpan.FromSeconds(1)) };
fadeInAnimation.Completed += FadeInAnimation_Completed;
myStoryboard = new Storyboard();
myStoryboard.Children.Add(fadeInAnimation);
Storyboard.SetTargetName(fadeInAnimation, MyRectangle.Name);
Storyboard.SetTargetProperty(fadeInAnimation, new PropertyPath(Rectangle.OpacityProperty));
// Use the Loaded event to start the Storyboard.
MyRectangle.Loaded += new RoutedEventHandler(myRectangleLoaded);
}
private void myRectangleLoaded(object sender, RoutedEventArgs e)
{
myStoryboard.Begin(this);
}
private void FadeInAnimation_Completed(object sender, EventArgs e)
{
DispatcherTimer timerFadeOut = new DispatcherTimer();
timerFadeOut.Interval = TimeSpan.FromSeconds(2);
timerFadeOut.Tick += TimerFadeOut_Tick;
timerFadeOut.Start();
}
private void TimerFadeOut_Tick(object sender, EventArgs e)
{
DoubleAnimation fadeOutAnimation = new DoubleAnimation() { From = 1.0, To = 0.0, Duration = new Duration(TimeSpan.FromSeconds(1)) };
myStoryboard = new Storyboard();
myStoryboard.Children.Add(fadeOutAnimation);
Storyboard.SetTargetName(fadeOutAnimation, MyRectangle.Name);
Storyboard.SetTargetProperty(fadeOutAnimation, new PropertyPath(Rectangle.OpacityProperty));
myStoryboard.Begin(this);
}
This works. That being said I am open to corrections.
How can I convert this piece of XAML code to code-behind in C# as my from and to value changes dynamically?
XAML
<Window.Triggers>
<EventTrigger RoutedEvent="Window.Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation BeginTime="00:00:00"
From="200"
To="500"
Storyboard.TargetProperty="(Window.Top)"
AccelerationRatio=".1"
Duration="0:0:.2" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Window.Triggers>
You don't need Storyboard from code behind, that can be done only with DoubleAnimation.
public MainWindow()
{
InitializeComponent();
Loaded += (s, e) =>
{
DoubleAnimation animation = new DoubleAnimation(200, 500,
TimeSpan.FromSeconds(0.2));
animation.AccelerationRatio = 0.1;
BeginAnimation(Window.TopProperty, animation);
};
}
Try this:
XAML
<Window x:Class="CreateAnimationinCodeHelp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Name="MyWindow" Loaded="Window_Loaded"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Label Background="AliceBlue" Content="Test" />
</Grid>
</Window>
Code-behind
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Storyboard sb = new Storyboard();
DoubleAnimation doubleAnimation = new DoubleAnimation();
doubleAnimation.From = 200;
doubleAnimation.To = 500;
doubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(0.2));
doubleAnimation.AccelerationRatio = 0.1;
Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("(Window.Top)"));
sb.Children.Add(doubleAnimation);
MyWindow.BeginStoryboard(sb);
}
}
I'm working on a Windows Phone app and i create storyboard that changes position an image.But i have an error.
An exception of type 'System.InvalidOperationException' occurred in System.Windows.ni.dll but was not handled in user code storyboard
This is my code:
XAML:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0" MouseMove="Mouse_Move">
<Grid.Resources>
<Storyboard x:Name="sbimg">
<PointAnimation x:Name="animationimg" Duration="0:0:0.1"
Storyboard.TargetName="earimg" />
</Storyboard>
</Grid.Resources>
<Image x:Name="earimg" Height="30" Width="30"
Source="1.png" Margin="0,0,426,577">
</Image>
</Grid>
And C#:
private void Mouse_Move(object sender, System.Windows.Input.MouseEventArgs e)
{
double pointX = e.GetPosition(null).X;
double pointY = e.GetPosition(null).Y;
Point mypoint = new Point(pointX,pointY);
animationimg.To = mypoint;
sbimg.Begin();
}
To accomplish this task I suggest to use a Canvas as LayoutRoot and a GestureListner from Windows Phone Toolkit to catch user gestures. Your XAML should looks like this
<Canvas x:Name="LayoutRoot"
Background="Transparent">
<toolkit:GestureService.GestureListener>
<toolkit:GestureListener
x:Name="SurfaceGestureListner"
Tap="SurfaceGestureListner_OnTap"
DragDelta="GestureListnerDragDelta"/>
</toolkit:GestureService.GestureListener>
<Image
x:Name="MyImage"
Source="/Assets/ApplicationIcon.png" Height="100" Width="100">
<Image.RenderTransform>
<TranslateTransform x:Name="TranslateTransform"/>
</Image.RenderTransform>
</Image>
</Canvas>
And in code behind
private Storyboard GenerateMoveAnimation(double x, double y)
{
var xAnimation = new DoubleAnimation
{
From = TranslateTransform.X,
To = x
};
var yAnimation = new DoubleAnimation
{
From = TranslateTransform.Y,
To = y
};
Storyboard.SetTarget(xAnimation, TranslateTransform);
Storyboard.SetTargetProperty(xAnimation, new PropertyPath("X"));
Storyboard.SetTarget(yAnimation, TranslateTransform);
Storyboard.SetTargetProperty(yAnimation, new PropertyPath("Y"));
var str = new Storyboard();
str.Children.Add(xAnimation);
str.Children.Add(yAnimation);
return str;
}
private void GestureListnerDragDelta(object sender, DragDeltaGestureEventArgs e)
{
var point = e.GetPosition(LayoutRoot);
GenerateMoveAnimation(point.X, point.Y).Begin();
}
private void SurfaceGestureListner_OnTap(object sender, Microsoft.Phone.Controls.GestureEventArgs e)
{
var point = e.GetPosition(LayoutRoot);
GenerateMoveAnimation(point.X, point.Y).Begin();
}
I have a grid of images and buttons, and I want to animate motion from one position to another (actually a few spaces to the left) automatically, but it hasn't worked. I've tried using a storyboard in xaml and programatically as in the code below, but its now working. Please help!!!
public static void MoveTo(Grid target)
{
Canvas.SetLeft(target, 0);
var top = Canvas.GetTop(target);
var left = Canvas.GetLeft(target);
TranslateTransform trans = new TranslateTransform();
target.RenderTransform = trans;
double newX = (double)(left - 300);
double newY = (double)top;
DoubleAnimation anim1 = new DoubleAnimation(top, -15, TimeSpan.FromSeconds(10));
//DoubleAnimation anim1 = new DoubleAnimation(top, newY - top, TimeSpan.FromSeconds(10));
DoubleAnimation anim2 = new DoubleAnimation(left, newX - left, TimeSpan.FromSeconds(10));
anim1.AutoReverse = true;
anim1.RepeatBehavior = RepeatBehavior.Forever;
trans.BeginAnimation(TranslateTransform.XProperty, anim1);
trans.BeginAnimation(TranslateTransform.YProperty, anim2);
}
totally TranslateTransform isnt good for that you want .better to use thinkness animation
i advise you dont use canavas and change it to grid but if you use canavas use this code
private void Animationsss(Grid grd)
{
//create an animation
DoubleAnimation da = new DoubleAnimation();
//set from animation to start position
//dont forget set canvas.left for grid if u dont u will get error
da.From = Canvas.GetLeft(grd);
//set second position of grid
da.To = -100;
//set duration
da.Duration = new Duration(TimeSpan.FromSeconds(2));
//run animation if u want stop ,start etc use story board
grd.BeginAnimation(Canvas.LeftProperty, da);
}
if you use grid code is this :
private void Animation(Grid grd)
{
ThicknessAnimation ta = new ThicknessAnimation();
//your first place
ta.From = grd.Margin;
//this move your grid 1000 over from left side
//you can use -1000 to move to left side
ta.To = new Thickness(1000, 0, 0, 0);
//time the animation playes
ta.Duration = new Duration(TimeSpan.FromSeconds(10));
//dont need to use story board but if you want pause,stop etc use story board
grd.BeginAnimation(Grid.MarginProperty, ta);
}
you can use opacity animation for fade your grid ... it show good if move and fade !
private void Animationsss(Grid grd)
{
DoubleAnimation da = new DoubleAnimation(1, 0, new Duration(TimeSpan.FromSeconds(2)));
grd.BeginAnimation(Grid.OpacityProperty, da);
}
if there isnt any reason u can change canavas to grid and also better use TranslateTransform for resize controls like code below this code resize control if mouse enter in it :
private void grid1_MouseEnter(object sender, MouseEventArgs e)
{
//at first its normal size
ScaleTransform st = new ScaleTransform(1, 1);
//animation size to 1.25 persent of real size
DoubleAnimation da = new DoubleAnimation(1,1.25, new Duration(TimeSpan.FromSeconds(2)));
//set transform to control
grid1.RenderTransform = st;
//animation transform now From Y And X
st.BeginAnimation(ScaleTransform.ScaleXProperty, da);
st.BeginAnimation(ScaleTransform.ScaleYProperty, da);
}
if you animation for width or height do same work like scale transform :)
hope i can help you ...:))
leave comment for me please
You can also use xaml for this:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="TestBed.MainWindow"
x:Name="Window"
Title="MainWindow"
Width="640" Height="480">
<Window.Resources>
<Storyboard x:Key="MoveGrid">
<ThicknessAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Margin)" Storyboard.TargetName="grid">
<EasingThicknessKeyFrame KeyTime="0:0:1" Value="-300,0,0,0"/>
</ThicknessAnimationUsingKeyFrames>
</Storyboard>
</Window.Resources>
<Window.Triggers>
<EventTrigger RoutedEvent="ButtonBase.Click" SourceName="button">
<BeginStoryboard x:Name="MoveGrid_BeginStoryboard" Storyboard="{StaticResource MoveGrid}"/>
</EventTrigger>
</Window.Triggers>
<Canvas>
<Grid x:Name="grid" Height="300" Width="300" Background="Black">
<Button x:Name="button" Content="Move the gird!" Height="30" Margin="10,0" />
</Grid>
</Canvas>
</Window>