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);
}
}
Related
I am having problem in constructing the in-code program based on the given xaml code. Especially for the Transform Group part and the Trigger part.
<Window x:Class="newStackOverflow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:newStackOverflow"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Storyboard x:Key="Storyboard1">
<DoubleAnimationUsingKeyFrames
Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)"
Storyboard.TargetName="rectangle">
<EasingDoubleKeyFrame KeyTime="0:0:10" Value="300"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Canvas x:Name="canvas" VerticalAlignment="Stretch" Background="Green">
<Rectangle x:Name="rectangle"
Fill="#FFF4F4F5" Stroke="Black"
Height="100" Width="100"
Canvas.Left="10" Canvas.Top="10"
RenderTransformOrigin="0.5,0.5">
<Rectangle.RenderTransform>
<TransformGroup>
<ScaleTransform ScaleX="1"/>
<TranslateTransform X="50" Y="20"/>
</TransformGroup>
</Rectangle.RenderTransform>
</Rectangle>
</Canvas>
<Button Content="Button"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Padding="10 5" Margin="10" Grid.Row="1">
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<BeginStoryboard Storyboard="{StaticResource Storyboard1}"/>
</EventTrigger>
</Button.Triggers>
</Button>
</Grid>
Can you give any ideas in developing the in-code part?Thanks in advance!:D
these are my codes. When i tried the codes, it say that the s.Begin(rectangle) exception user unhandled.
public partial class MainWindow : Window
{
private Storyboard s;
public MainWindow()
{
InitializeComponent();
Button button = new Button();
button.Height = 28;
button.Width = 58;
button.HorizontalAlignment = HorizontalAlignment.Center;
button.VerticalAlignment = VerticalAlignment.Center;
button.Content = "Button";
button.Name = "button";
this.RegisterName(button.Name, button);
Rectangle rectangle = new Rectangle();
rectangle.Width = 100;
rectangle.Height = 100;
rectangle.Fill = new SolidColorBrush(Colors.White);
rectangle.Stroke = new SolidColorBrush(Colors.Black);
Canvas.SetLeft(rectangle, 10);
Canvas.SetTop(rectangle,10);
canvas1.Children.Add(rectangle);
rectangle.Name = "rectangle";
TranslateTransform tt = new TranslateTransform();
ScaleTransform st = new ScaleTransform();
TransformGroup tg = new TransformGroup();
tg.Children.Add(tt);
tg.Children.Add(st);
button.RenderTransform = tg;
Duration duration = new Duration(TimeSpan.FromMilliseconds(10));
DoubleAnimationUsingKeyFrames myDoubleAnim = new DoubleAnimationUsingKeyFrames();
EasingDoubleKeyFrame myDoubleKey = new EasingDoubleKeyFrame();
Storyboard s = new Storyboard();
Storyboard.SetTargetName(myDoubleAnim, button.Name);
Storyboard.SetTargetProperty(myDoubleAnim, new PropertyPath("RenderTransform.Children[3].Y"));
myDoubleKey.KeyTime = KeyTime.FromPercent(1);
myDoubleKey.Value = 300;
myDoubleAnim.KeyFrames.Add(myDoubleKey);
s.Children.Add(myDoubleAnim);
s.Begin(rectangle);
//button.Loaded += new RoutedEventHandler(buttonLoaded);
}
I have creaed flipview in XAML page i want to make that slides transtaction automatically how can i do that?
<StackPanel x:Name="StackPanel_1" Margin="541,42,71,160" Orientation="Vertical" Grid.Row="1">
<FlipView x:Name="flipView1" Width="480" Height="270"
BorderBrush="Black" BorderThickness="1">
<Grid Margin="0,0,-8,-8">
<Image Source="Assets/Logo.png" Width="480" Height="270" Stretch="UniformToFill"/>
<Border Background="#A5000000" Height="80" VerticalAlignment="Bottom">
<TextBlock Text="Logo" FontFamily="Segoe UI" FontSize="26.667" Foreground="#CCFFFFFF" Padding="15,20" Margin="0,0,8,8"/>
</Border>
</Grid>
<Grid Margin="0,0,-8,-8">
<Image Source="Assets/SplashScreen.png" Width="480" Height="270" Stretch="UniformToFill" />
<Border Background="#A5000000" Height="80" VerticalAlignment="Bottom">
<TextBlock Text="Logo11111111" FontFamily="Segoe UI" FontSize="26.667" Foreground="#CCFFFFFF" Padding="15,20" Margin="0,0,8,8"/>
</Border>
</Grid>
<Grid Height="270" Width="480">
<Image Source="Assets/SmallLogo.png" Width="480" Height="270" Stretch="UniformToFill" />
<Border Background="#A5000000" Height="80" VerticalAlignment="Bottom">
<TextBlock Text="Logo222222222" FontFamily="Segoe UI" FontSize="26.667" Foreground="#CCFFFFFF" Padding="15,20" Margin="0,0,8,8"/>
</Border>
</Grid>
</FlipView>
You'll need to update the flipview's SelectedIndex property.
The most straightforward would be to run a DispatcherTimer and increment SelectedIndex every however long you'd like. When it gets to the end then set it back to 0. The hitch is that the FlipView will animate when you switch the index by one, but not when you jump pages. If you want to loop back from the last page to the first it will jump rather than animate. You might want to reverse direction instead of going direct to 0.
int change = 1;
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(2);
timer.Tick += (o, a) =>
{
// If we'd go out of bounds then reverse
int newIndex = flipView1.SelectedIndex + change;
if (newIndex >= flipView1.Items.Count || newIndex < 0)
{
change *= -1;
}
flipView1.SelectedIndex += change;
};
timer.Start();
If you want to set this up completely in XAML without code then you can create a Storyboarded animation in Xaml to animate the SelectedIndex and trigger it with an EventTriggerBehavior behavior when page loads.
<Page.Resources>
<Storyboard x:Name="AutoFlipView" RepeatBehavior="Forever" AutoReverse="True">
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(Selector.SelectedIndex)" Storyboard.TargetName="flipView1">
<DiscreteObjectKeyFrame KeyTime="0">
<DiscreteObjectKeyFrame.Value>
<x:Int32>0</x:Int32>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
<DiscreteObjectKeyFrame KeyTime="0:0:1">
<DiscreteObjectKeyFrame.Value>
<x:Int32>1</x:Int32>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
<DiscreteObjectKeyFrame KeyTime="0:0:2">
<DiscreteObjectKeyFrame.Value>
<x:Int32>2</x:Int32>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
<DiscreteObjectKeyFrame KeyTime="0:0:3">
<DiscreteObjectKeyFrame.Value>
<x:Int32>2</x:Int32>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</Page.Resources>
<Interactivity:Interaction.Behaviors>
<Core:EventTriggerBehavior EventName="Loaded">
<Media:ControlStoryboardAction Storyboard="{StaticResource AutoFlipView}"/>
</Core:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>
I wrote a hacky prototype that shows how you can animate the entire cycle by rearranging the elements in the FlipView...
C#
using System.Collections;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace App4
{
public class CyclingFlipView : FlipView
{
public async Task Cycle()
{
if (this.ItemsSource != null)
{
var list = (IList)this.ItemsSource;
if (list.Count == 0)
{
return;
}
SelectionChangedEventHandler handler = null;
var tcs = new TaskCompletionSource<bool>();
handler = (s, e) =>
{
tcs.SetResult(true);
this.SelectionChanged -= handler;
};
this.SelectionChanged += handler;
this.SelectedIndex = (this.SelectedIndex + 1) % list.Count;
await tcs.Task;
await Task.Delay(500);
var i = this.SelectedIndex;
this.SelectedItem = null;
var item = list[0];
list.RemoveAt(0);
list.Add(item);
this.SelectedIndex = i - 1;
}
else if (this.Items != null)
{
if (this.Items.Count == 0)
{
return;
}
SelectionChangedEventHandler handler = null;
var tcs = new TaskCompletionSource<bool>();
handler = (s, e) =>
{
tcs.SetResult(true);
this.SelectionChanged -= handler;
};
this.SelectionChanged += handler;
this.SelectedIndex = (this.SelectedIndex + 1) % this.Items.Count;
await tcs.Task;
await Task.Delay(500);
var i = this.SelectedIndex;
this.SelectedItem = null;
var item = this.Items[0];
this.Items.RemoveAt(0);
this.Items.Add(item);
this.SelectedIndex = i - 1;
}
}
public async Task AutoCycle()
{
while (true)
{
this.Cycle();
await Task.Delay(1000);
}
}
}
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
var fv = new CyclingFlipView();
fv.ItemsSource = new ObservableCollection<int>(Enumerable.Range(0, 4));
fv.ItemTemplate = (DataTemplate)this.Resources["ItemTemplate"];
this.Content = fv;
fv.AutoCycle();
}
}
}
XAML
<Page
x:Class="App4.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App4"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.Resources>
<DataTemplate
x:Key="ItemTemplate">
<Border
Background="GreenYellow">
<TextBlock
Text="{Binding}"
FontSize="144"
VerticalAlignment="Center"
HorizontalAlignment="Center"/>
</Border>
</DataTemplate>
</Page.Resources>
<Grid
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
</Grid>
</Page>
I want to create a slideshow of images. For this I have loaded new images in image control after every set interval of time. But each time i load a new image it comes without any animation I need to load each image with a transition animation or fade in-out animation. How can I achieve animation while changing images in Image control? Following is the code:
XAML:
<Grid>
<Image Source="{Binding CurrentImage}" />
</Grid>
XAML.cs
ViewModel = new ScreenSaverViewModel();
this.DataContext = ViewModel;
ViewModel.cs
/// <summary>
/// Gets the current image to display on the attract screen. Changes to this property
/// cause the PropertyChanged event to be signaled
/// </summary>
public string CurrentImage
{
get { return this.currentImage; }
protected set
{
this.currentImage = value;
this.OnPropertyChanged("CurrentImage");
}
}
/// <summary>
/// Gets the observable collection of all images.
/// </summary>
public ObservableCollection<string> Images
{
get { return this.images; }
}
public ScreenSaverViewModel()
{
images = new ObservableCollection<string>();
this.LoadSlideShowImages();
if (Images != null && Images.Count > 0)
{
this.CurrentImage = this.Images[this.currentIndex];
this.tickTimer = new DispatcherTimer();
this.tickTimer.Interval = TimeSpan.FromMilliseconds(TimerIntervalMilliseconds);
this.tickTimer.Tick += (s, e) =>
{
this.currentIndex++;
this.currentIndex = this.currentIndex < this.Images.Count ? this.currentIndex : 0;
this.CurrentImage = this.Images[this.currentIndex];
};
// start the timer after image is loaded
this.tickTimer.Start();
}
}
I have created a class inheriting Image control in which I have raised property change when Source of image control changes. on which I have applied trigger this works fine now. Following is the code:
<controls:ImageControl Source="{Binding CurrentImage}" >
<controls:ImageControl.Triggers>
<EventTrigger RoutedEvent="controls:ImageControl.SourceChanged">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="(Image.Opacity)" From="0" To="1" Duration="0:0:1" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</controls:ImageControl.Triggers>
</controls:ImageControl>
public class ImageControl : Image
{
public static readonly RoutedEvent SourceChangedEvent = EventManager.RegisterRoutedEvent(
"SourceChanged", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(ImageControl));
static ImageControl()
{
Image.SourceProperty.OverrideMetadata(typeof(ImageControl), new FrameworkPropertyMetadata(SourcePropertyChanged));
}
public event RoutedEventHandler SourceChanged
{
add { AddHandler(SourceChangedEvent, value); }
remove { RemoveHandler(SourceChangedEvent, value); }
}
private static void SourcePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
Image image = obj as Image;
if (image != null)
{
image.RaiseEvent(new RoutedEventArgs(SourceChangedEvent));
}
}
}
Hope this helps.
Please run this code separately.
<Grid Height="200" Width="200">
<Grid.Triggers>
<EventTrigger RoutedEvent="Loaded">
<BeginStoryboard >
<Storyboard >
<ObjectAnimationUsingKeyFrames Duration="00:00:06" RepeatBehavior="Forever" Storyboard.TargetName="img1" Storyboard.TargetProperty="(Image.Source)">
<DiscreteObjectKeyFrame KeyTime="00:00:00">
<DiscreteObjectKeyFrame.Value>
<BitmapImage UriSource="image1.png" />
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
<DiscreteObjectKeyFrame KeyTime="00:00:02">
<DiscreteObjectKeyFrame.Value>
<BitmapImage UriSource="image2.png" />
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
<DiscreteObjectKeyFrame KeyTime="00:00:04">
<DiscreteObjectKeyFrame.Value>
<BitmapImage UriSource="image3.png" />
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
<DoubleAnimation Storyboard.TargetName="img1" RepeatBehavior="Forever" Storyboard.TargetProperty="Opacity" From="0.1" To="1" Duration="00:00:02"></DoubleAnimation>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Grid.Triggers>
<Image x:Name="img1" Stretch="Fill"></Image>
</Grid>
Update
<Storyboard FillBehavior="Stop" x:Key="FadeOut">
<DoubleAnimation FillBehavior="Stop" Storyboard.TargetName="ScreensaverImage" Storyboard.TargetProperty="Opacity" From="0.05" To="1" Duration="0:0:2">
</DoubleAnimation>
</Storyboard>
<Storyboard FillBehavior="Stop" x:Key="FadeIn">
<DoubleAnimation Storyboard.TargetName="ScreensaverImage" FillBehavior="Stop" Storyboard.TargetProperty="Opacity" From="1" To=".05" Duration="0:0:2">
</DoubleAnimation>
</Storyboard>
<Grid>
<Image x:Name="ScreensaverImage"></Image>
</Grid>
public partial class MainWindow : Window
{
List<Uri> savedImage = new List<Uri>();
int i = 0;
Storyboard fadeIn, fadeOut;
public MainWindow()
{
InitializeComponent();
this.Loaded += MainWindow_Loaded;
savedImage.Add(new Uri("image1.png", UriKind.Relative));
savedImage.Add(new Uri("image2.png", UriKind.Relative));
savedImage.Add(new Uri("image3.png", UriKind.Relative));
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
if (savedImage.Count > 0)
{
fadeIn = (Storyboard)this.Resources["FadeIn"];
fadeOut = (Storyboard)this.Resources["FadeOut"];
fadeIn.Completed += fadeIn_Completed;
fadeOut.Completed += fadeOut_Completed;
ScreensaverImage.Source = new BitmapImage(savedImage[i++]);
if (savedImage.Count > 1)
{
BeginStoryboard(fadeOut);
}
ScreensaverImage.Visibility = System.Windows.Visibility.Visible;
}
else
{
ScreensaverImage.Visibility = System.Windows.Visibility.Collapsed;
}
}
void fadeOut_Completed(object sender, EventArgs e)
{
fadeIn.Begin();
}
void fadeIn_Completed(object sender, EventArgs e)
{
if (i == savedImage.Count)
i = 0;
ScreensaverImage.Source = new BitmapImage(savedImage[i++]);
fadeOut.Begin();
}
}
you can use the MetroImageControl or MetroContentControl that provided in:
Mahapps library for metro style
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>
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();
}