Refreshing canvas - c#

I have a question about refreshing canvas. There is .Refresh() or .Clear() in WinForms.But what about WPF?
I watched some methods how to do it, but it didn't help me at all.
The situation is that my canvas contains textBox and Button. When I click button I can draw some ellipses.
And I need to clear these ellipses after my every click on button but without clearing textBox and Button from this Canvas!
My WPF Xaml:
<Window x:Class="draw.CreateEllipse"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Create" Height="768" Width="1024" WindowStartupLocation="CenterScreen" Name="Create" Closed="Create_Closed">
<Canvas Name="can" Background="White" MouseDown="can_MouseDown">
<TextBox Name="txbNumber" Height="34" Canvas.Left="797" TextWrapping="Wrap" Text="5" Canvas.Top="76" Width="209" FontSize="18"/>
<Button Name="btnCreate" Content="Create" Canvas.Left="797" Canvas.Top="130" Width="209" Height="66" FontSize="18" Click="btnCreate_Click"/>
</Canvas>
My C# :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace draw
{
/// <summary>
/// Логика взаимодействия для CreateGraph.xaml
/// </summary>
public partial class Create : Window
{
public Create()
{
InitializeComponent();
}
int n, i;
Ellipse[] v;
Rectangle rect = new Rectangle();
SolidColorBrush solidcolor = new SolidColorBrush();
private void btnCreate_Click(object sender, RoutedEventArgs e)
{
n = Convert.ToInt16(txbNumber.Text);
v = new Ellipse[n];
//can.Children.Clear();
}
private void Create_Closed(object sender, EventArgs e)
{
Application.Current.Shutdown();
}
private void can_MouseDown(object sender, MouseButtonEventArgs e)
{
solidcolor.Color = Colors.Transparent;
//Ellipse myEllipse = new Ellipse();
SolidColorBrush mySolidColorBrush = new SolidColorBrush();
for (i = 0; i < n; i++)
{
v[i] = new Ellipse();
mySolidColorBrush.Color = Colors.Transparent;
v[i].Fill = mySolidColorBrush;
v[i].StrokeThickness = 2;
v[i].Stroke = Brushes.Black;
v[i].Width = 75;
v[i].Height = 75;
v[i].Margin = new Thickness(e.GetPosition(can).X, e.GetPosition(can).Y, 0, 0);
can.Children.Add(v[i]);
}
if (n <= 0)
return;
n--;
}
}
}

you can separate your elements with this code:
var can2 = can.Children.OfType<Ellipse>();
above code select all of Ellipses in your Canvas "can".
and you can remove them from your Canvas Like this:
foreach (var element in can2)
{
can.Children.Remove(element);
}
Now you have no ellipse in your Canvas.
Hope this helps you.

Related

C# WPF ellipse bouncing on rectangle

I'm trying to make a solo pong game for a school project, but I don't know how to handle the ellipse bouncing on the rectangle. They're both inside a canvas as you can see in the XAML, I'll leave my code, please I need help, because I'm stuck at this point.
I tried different ways, but I can't figure it out, so any tip will be helpful!
<Window x:Class="PongSolo.Game"
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:PongSolo"
mc:Ignorable="d"
Title="Game" Height="450" Width="650" Closing="Game_Closing" WindowStartupLocation="CenterScreen" Loaded="Window_Loaded">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition Height="5*"></RowDefinition>
</Grid.RowDefinitions>
<Border Name="superBorder" BorderBrush="Black" BorderThickness="10" Grid.Row="1">
<Canvas Name="superCanvas">
<Rectangle x:Name="superRect" Fill="Blue" Width="100" Height="15" Canvas.Bottom="0" Canvas.Left="0"/>
<Ellipse x:Name="superElly" Fill="Purple" Width="20" Height="20" Grid.Row="1" Canvas.Top="0" Canvas.Left="0"/>
</Canvas>
</Border>
<Label Content="Punteggio:" FontWeight="Bold" FontSize="20" Grid.Row="0"/>
<Label Content="0" Name="scoreLabel" FontWeight="Bold" FontSize="20" Grid.Row="0" Margin="119,0,-119,0"/>
</Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace PongSolo
{
/// <summary>
/// Logica di interazione per Game.xaml
/// </summary>
public partial class Game : Window
{
SoundPlayer sound = new System.Media.SoundPlayer(Environment.CurrentDirectory+"/Resources/bgm_new.wav");
DispatcherTimer playerDispatcher = new DispatcherTimer();
DispatcherTimer ballDispatcher = new DispatcherTimer();
int score = 0;
double startxspeed = 4;
double startyspeed = 4;
public Game()
{
InitializeComponent();
playerDispatcher.Interval = TimeSpan.FromMilliseconds(10);
ballDispatcher.Interval = TimeSpan.FromMilliseconds(10);
ballDispatcher.Tick += ballMovement;
playerDispatcher.Tick += playerMovement;
playerDispatcher.Start();
ballDispatcher.Start();
}
private void ballMovement(object sender, EventArgs e)
{
double xspeed = Canvas.GetLeft(superElly) + startxspeed;
double yspeed = Canvas.GetTop(superElly) + startyspeed;
//Ball collision with rectangle
if(/*bouncing statement*/)
{
score++;
scoreLabel.Content = score.ToString();
startyspeed *= -1;
}
//up collision
if (yspeed < (superCanvas.ActualHeight - (superElly.ActualHeight / 2)) && yspeed > 0)
Canvas.SetTop(superElly, yspeed);
else
{
startyspeed *= -1;
}
//down collision
if(yspeed >= (superCanvas.ActualHeight - (superElly.ActualHeight/2)) && yspeed >0)
{
playerDispatcher.Stop();
ballDispatcher.Stop();
}
//lateral collision
if (xspeed < (superCanvas.ActualWidth - (superElly.ActualWidth / 2 + 10)) && xspeed > 0)
Canvas.SetLeft(superElly, xspeed);
else
{
startxspeed *= -1;
}
}
private void playerMovement(object sender, EventArgs e)
{
double xvalue = Canvas.GetLeft(superRect) + 3;
if (Keyboard.IsKeyDown(Key.Left))
{
if (!outOfBoundaries("left"))
MovePlayerLeft();
}
if (Keyboard.IsKeyDown(Key.Right))
{
if (!outOfBoundaries("right"))
MovePlayerRight();
}
}
public bool outOfBoundaries(string s)
{
bool is_out_of_boundaries = false;
switch (s)
{
case "left":
{
if (Canvas.GetLeft(superRect) <= 0)
is_out_of_boundaries = true;
break;
}
case "right":
{
if (Canvas.GetLeft(superRect) >= superCanvas.ActualWidth-superRect.Width)
is_out_of_boundaries = true;
break;
}
default:
break;
}
return is_out_of_boundaries;
}
private void MovePlayerRight()
{
Canvas.SetLeft(superRect, Canvas.GetLeft(superRect) + 5);
}
private void MovePlayerLeft()
{
Canvas.SetLeft(superRect, Canvas.GetLeft(superRect) - 5);
}
private void Game_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
App.Current.Shutdown();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.MinHeight = 300;
this.MinWidth = 300;
PlayMusic();
}
private void PlayMusic()
{
sound.PlayLooping();
}
}
}

Attach Mouse Events to Rect WPF

I have the following program that creates Rectangle using Rect object. I want to attach Mouse events to newly created Rect. How can I do that? Please help. Here's the code below.
XAML
<Window x:Class="TestDrawing.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:TestDrawing"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid Margin="12">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Orientation="Horizontal">
<Canvas>
<Button x:Name="BtnAddRectangle" Content="Add Rectngle" Click="BtnAddRectangle_Click" Height="20"/>
</Canvas>
</StackPanel>
<Canvas Name="canvas">
</Canvas>
</Grid>
CS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace TestDrawing
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
bool drag = false;
Point startPoint;
public MainWindow()
{
InitializeComponent();
}
// this creates and adds rectangles dynamically
private void BtnAddRectangle_Click(object sender, RoutedEventArgs e)
{
DrawingVisual drawingVisual = new DrawingVisual();
// Retrieve the DrawingContext in order to create new drawing content.
DrawingContext drawingContext = drawingVisual.RenderOpen();
// Create a rectangle and draw it in the DrawingContext.
Rect rect = new Rect(new Size(150, 100));
drawingContext.DrawRectangle(Brushes.LightBlue, null,rect);
drawingContext.Close();
canvas.Children.Add(new VisualHost { Visual = drawingVisual });
foreach (UIElement child in canvas.Children)
{
//Not working
child.MouseDown += rectangle_MouseDown;
child.MouseMove += rectangle_MouseMove;
}
}
private void rectangle_MouseDown(object sender, MouseButtonEventArgs e)
{
// start dragging
drag = true;
// save start point of dragging
startPoint = Mouse.GetPosition(canvas);
}
private void rectangle_MouseMove(object sender, MouseEventArgs e)
{
// if dragging, then adjust rectangle position based on mouse movement
if (drag)
{
Rectangle draggedRectangle = sender as Rectangle;
Point newPoint = Mouse.GetPosition(canvas);
double left = Canvas.GetLeft(draggedRectangle);
double top = Canvas.GetTop(draggedRectangle);
Canvas.SetLeft(draggedRectangle, left + (newPoint.X - startPoint.X));
Canvas.SetTop(draggedRectangle, top + (newPoint.Y - startPoint.Y));
startPoint = newPoint;
}
}
private void rectangle_MouseUp(object sender, MouseButtonEventArgs e)
{
// stop dragging
drag = false;
}
}
public class VisualHost : UIElement
{
public Visual Visual { get; set; }
protected override int VisualChildrenCount
{
get { return Visual != null ? 1 : 0; }
}
protected override Visual GetVisualChild(int index)
{
return Visual;
}
}
}
Here's a quote from the MSDN page on Using DrawingVisual Objects:
The DrawingVisual is a lightweight drawing class that is used to render shapes, images, or text. This class is considered lightweight because it does not provide layout or event handling, which improves its performance. For this reason, drawings are ideal for backgrounds and clip art.
If you need event handling, why not just use the existing Rectangle class? Your existing code can be easily changed to use this class instead of your custom VisualHost.
private void BtnAddRectangle_Click(object sender, RoutedEventArgs e)
{
Rectangle rect = new Rectangle() { Fill = Brushes.LightBlue, Width = 150, Height = 100 };
canvas.Children.Add(rect);
foreach (UIElement child in canvas.Children)
{
child.MouseDown += rectangle_MouseDown;
child.MouseMove += rectangle_MouseMove;
}
}

Add items to a Thumb dynamically

I created a two thumbs dynamically that look like rectangles and handled the drag and drop events so they can move inside a Canvas. Later when I press some button on the UI, I want to add some strings dynamically to each Thumb inside the Canvas. Is there a way to do it. Please help.
Xaml:
<uwpControls:LayoutTransformControl x:Name="MainLayoutControl" Grid.Row="4" Height="400" Width="600" HorizontalAlignment="Center" VerticalAlignment="Center">
<Grid Grid.Row="4" x:Name="gridBarImagePanel" BorderBrush="Black"
BorderThickness="2">
<Image x:Name="BarCodeImage"
RenderTransformOrigin="0.5,0.5"></Image>
<Canvas x:Name="cnvBarCodeImage">
</Canvas>
</Grid>
</uwpControls:LayoutTransformControl>
Code Behind:
private void CreateUIShapes(int numberOfWindows, List<Dimensions> dimensions)
{
Thumb th = null;
for (int i = 0; i < numberOfWindows; i++)
{
th = new Thumb();
th.Name = i.ToString();
var item = dimensions[i];
th.Width = item.Width;
th.Height = item.Height;
th.Foreground = new SolidColorBrush(Windows.UI.Colors.Transparent);
th.BorderBrush = item.BorderColor;
th.BorderThickness = new Thickness(3);
th.DragDelta += (sender, e) => Th_DragDelta(sender, e, dimensions);
th.DragCompleted += (sender, e) => Th_DragCompleted(sender, e, item.IsImageRotated);
//RotateWindowsByAngle(90, th, dimensions, i);
Canvas.SetLeft(th, item.left);
Canvas.SetTop(th, item.Top);
cnvBarCodeImage.Children.Add(th);
}
}
private void BtnScan_Click(object sender, RoutedEventArgs e)
{
//How can I add some text to the Thumb controls at this point. There is no Children Property.
}
Since the Thumb isn't a ContentControl, you will have to supply it with a custom ControlTemplate to add text to it.
Here is a simple example showing how to do this in code:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Markup;
using System.Windows.Media;
namespace WpfApp4
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var thumb = new Thumb
{
Width = 100,
Height = 50,
Background = new SolidColorBrush(Colors.Red),
Foreground = new SolidColorBrush(Colors.White),
Template = GetThumbTemplate("")
};
Canvas.SetLeft(thumb, 100);
Canvas.SetTop(thumb, 100);
RootCanvas.Children.Add(thumb);
thumb.Template = GetThumbTemplate("Hello world!");
}
private ControlTemplate GetThumbTemplate(string text)
{
var template = "<ControlTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" TargetType=\"Thumb\">" +
"<Border Background=\"{TemplateBinding Background}\">" +
"<TextBlock VerticalAlignment=\"Center\" HorizontalAlignment=\"Center\" Text=\"" + text + "\" />" +
"</Border>" +
"</ControlTemplate>";
return XamlReader.Parse(template) as ControlTemplate;
}
}
}
When I create the Thumb I set the Template with GetThumbTemplate and pass in an empty string. GetThumbTemplate creates a simple ControlTemplate with a Border and a TextBlock. I then parse the XAML and return it.
After I add it to the Canvas, I update the Template of the Thumb using the GetThumbTemplate method, passing in the string I want to display.
I hope this helps!

How to make an object to change color with MouseEnter and MouseLeave WPF

Well this is my WPF project and the problem is in this user control, People.xaml.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
namespace Projet
{
public partial class People : UserControl
{
Random rnd = new Random();
string filename = "C:\\Users\\Kristen\\peoples.txt";
public People()
{
InitializeComponent();
dataFromFile();
}
void dataFromFile()
{
if (!File.Exists(filename))
return;
var source = File.ReadLines(filename)
.Select(line => line.Split(' '))
.Select(m => new { name = m[0], length = int.Parse(m[1]) })
.OrderBy(x => x.length);
int k = 200;
foreach (var data in source)
{
Rectangle r = new Rectangle ();
r.Height = data.length;
r.Width = 25;
r.Fill = new SolidColorBrush(Colors.Red);
Canvas.SetLeft(r, k);
Canvas.SetBottom(r, 200);
board.Children.Add(r);
k += 50;
}
}
private void board_MouseEnter_1(object sender, MouseEventArgs e)
{
board.Background = Brushes.Blue;
//I have tried with r.Fill = new SolidColorBrush(Colors.Red); but it wont work either
dataFromFile();
}
private void juur_MouseLeave_1(object sender, MouseEventArgs e)
{
board.Background = Brushes.Yellow;
}
IT takes data out of file. In file there are people names and their heights. It makes those heights to bar chart using rectangles on canvas. I want to make the color of rectangles change with MouseEnter and MouseLeave but it just changes my canvas background color. I'll but my People.xaml here too just in case.
<UserControl x:Class="Project.People"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Canvas Background="Yellow" x:Name="board" MouseEnter="board_MouseEnter_1" MouseLeave="board_MouseLeave_1">
</Canvas>
You have to attach the event handlers to each Rectangle, not to the Canvas. Remove them here:
<Canvas Background="Yellow" x:Name="board"/>
Then add them to each Rectangle:
foreach (var data in source)
{
var r = new Rectangle();
r.MouseEnter += Rectangle_MouseEnter;
r.MouseLeave += Rectangle_MouseLeave;
...
}
...
private void Rectangle_MouseEnter(object sender, MouseEventArgs e)
{
((Rectangle)sender).Fill = Brushes.Blue;
}
private void Rectangle_MouseLeave(object sender, MouseEventArgs e)
{
((Rectangle)sender).Fill = Brushes.Yellow;
}
Having said that I'd strongly suggest to throw away all that code and use an MVVM approach instead. Perhaps start reading about ItemsControl and Data Templating.
There is absolutely no reason to use behind-code for this, just use a style and the IsMouseOver trigger (although in yoru case obviously change the setters to modify/replace the appropriate child control properties):
<Canvas>
<Canvas.Style>
<Style>
<Setter Property="Canvas.Background" Value="Yellow"/>
<Style.Triggers>
<Trigger Property="Canvas.IsMouseOver" Value="True">
<Setter Property="Canvas.Background" Value="Red" />
</Trigger>
</Style.Triggers>
</Style>
</Canvas.Style>
</Canvas>

how do compare a exactly position of MediaElement while playing

i have a single video (duration: 3 seconds) and i need to create 2 states
1- the video should always reach the second 1.5 and play it from the start.
TimeSpan ts = new TimeSpan(0, 0, 0, 1, 500);
TimeSpan ts_Start = new TimeSpan(0, 0, 0, 0, 0);
if (mediaElement.position == ts)
mediaElement.position = ts_Start; //doesnt work this block code
2- when i press a button, the video should play the full video (3 seconds). (simple flag, boolean)
so my question is, how do i know when the mediaelement.position = 1.5 seconds ??.... i thought of a method such as playing or something like that.
If you get the MediaElement's Clock property, you could attach onto the CurrentTimeInvalidated event and watch for the time to hit 1.5 seconds. The event has a lot of precision (i.e. it gets raised VERY often) so you don't want to do too much in response to the event unless you have to.
i resolved the problem... :) :) ....
i decide make me own application with many ideas that had taken of other forums.
My solution was easier than i planned, i used 2 videos, 2 mediaElements, a mediaEnded event and boolean variable to chage the video....
and works perfectly! Solution are here ------> (Solution, and coments)
in my app, i didn't have to use properties like clocks, TimeLines, DispatcherTimer, or any event like a CurrentTimeInvalidate, i just used the MediaEnded event and a boolean variable. :) no more. i have 2 videos (1,5 seconds and 3 seconds). when MediaEnded(media 1,5 seconds) mediaElement1,5sec.Position = TimeSpam.Zero; and MediElement3sec.Position = TimeSpam.Zero, and when i clicked the button, i just evaluated the variable (boolean) and play complet video of 3 seconds.
however, the source code are here: MainWindow.xaml
<Window x:Class="wpf_TestVideos.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="371" Width="525" Loaded="Window_Loaded">
<Grid>
<MediaElement Height="268" HorizontalAlignment="Left" Margin="141,12,0,0" Name="mediaElement15sec" VerticalAlignment="Top" Width="237" MediaEnded="mediaElement15sec_MediaEnded" />
<MediaElement Height="268" HorizontalAlignment="Left" Margin="142,12,0,0" Name="mediaElement3sec" VerticalAlignment="Top" Width="236" />
<Button Content="Load" Height="34" HorizontalAlignment="Left" Margin="12,286,0,0" Name="btLoad" VerticalAlignment="Top" Width="73" Click="btLoad_Click" />
<Button Content="Inicio Juego" Height="23" HorizontalAlignment="Left" Margin="128,286,0,0" Name="btStart" VerticalAlignment="Top" Width="86" Click="btStart_Click" />
<Button Content=""Reconoce Gesto"" Height="23" HorizontalAlignment="Left" Margin="285,286,0,0" Name="btGesture" VerticalAlignment="Top" Width="108" Click="btGesture_Click" />
</Grid>
MainWindow.xaml.cs:
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Navigation;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Interop;
using System.Windows.Media.Animation;
using System.Threading;
namespace wpf_TestVideos
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
string VideoLocation = System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
string sFileName = "";
string sFileName2 = "";
bool bVideoLoop = true;
TranslateTransform trans = new TranslateTransform();
private void btLoad_Click(object sender, RoutedEventArgs e)
{
mediaElement15sec.LoadedBehavior = MediaState.Manual;
mediaElement3sec.LoadedBehavior = MediaState.Manual;
btGesture.IsEnabled = true;
btStart.IsEnabled = true;
btLoad.IsEnabled = false;
DirectoryInfo df = new DirectoryInfo(VideoLocation);
if (df.Exists)
{
sFileName = VideoLocation + #"\Krown_test_loop.mov";
mediaElement15sec.Source = new Uri(sFileName);
mediaElement15sec.Stretch = Stretch.Fill;
sFileName2 = VideoLocation + #"\Krown_test_7.mov";
mediaElement3sec.Source = new Uri(sFileName2);
mediaElement3sec.Stretch = Stretch.Fill;
}
else
{
System.Windows.Forms.MessageBox.Show("No se puede cargar el video", "TestAll");
}
}
private void btStart_Click(object sender, RoutedEventArgs e)
{
mediaElement15sec.Position = TimeSpan.Zero;
mediaElement3sec.Position = TimeSpan.Zero;
mediaElement15sec.Play();
mediaElement3sec.Play();
bVideoLoop = true;
//VisualStateManager.GoToState(mediaElement15sec, "Bring1,5ToFront", true);
}
private void mediaElement15sec_MediaEnded(object sender, RoutedEventArgs e)
{
if (bVideoLoop)
{
mediaElement15sec.Position = TimeSpan.Zero;
mediaElement3sec.Position = TimeSpan.Zero;
}
}
private void btGesture_Click(object sender, RoutedEventArgs e)
{
bVideoLoop = false;
//Animacion_Opacidad(bVideoLoop);
//VisualStateManager.GoToState(mediaElement3sec, "Bring300ToFront", true);
}
private void Animacion_Opacidad(bool bLoop)
{
mediaElement15sec.RenderTransform = trans;
if (!bLoop)
{
DoubleAnimation anim1 = new DoubleAnimation(1, 0, TimeSpan.FromSeconds(1));
trans.BeginAnimation(OpacityProperty, anim1);
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
btGesture.IsEnabled = false;
btStart.IsEnabled = false;
btLoad.IsEnabled = true;
}
}
}
The accepted solution seems to be more a workaround than a solution.. what in case once you will need to use not 1.5 but another time, eg. 2.5 seconds? will you have to change the videos? The solution could be using a DistpatcherTimer:
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1.5); // your time
timer.Tick += timer_Tick;
timer.Start();
mePlayer.Play(); // run timer and player at same time
When the timer_Tick is reached just set the position to zero and call Play() again:
void timer_Tick(object sender, EventArgs e)
{
mePlayer.Position = new TimeSpan(0, 0, 0, 0);
mePlayer.Play();
}
And when clicking the second button, detach the timer (... can be attached later when necessary):
timer.Tick -= timer_Tick;

Categories