IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C# Discussion :

C# WPF : mettre le code en attente d'une animation.


Sujet :

C#

  1. #1
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2015
    Messages
    7
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Algérie

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Enseignement

    Informations forums :
    Inscription : Avril 2015
    Messages : 7
    Points : 5
    Points
    5
    Par défaut C# WPF : mettre le code en attente d'une animation.
    Bonjour à tous,
    Comment faire pour attendre la fin d'une animation pour executer le reste du code ?
    Par exemple :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
     
     
    Storyboard str = new Storyboard();
    //----
    //---
    //--
    str.Begin();
     
    // On veut que le reste s'éxecute aprés la fin du str et pas en paralèlle !!
     
    while()
    {
          //---
    }
    //---
    //--

  2. #2
    Expert confirmé
    Inscrit en
    Avril 2008
    Messages
    2 564
    Détails du profil
    Informations personnelles :
    Âge : 64

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 564
    Points : 4 441
    Points
    4 441
    Par défaut
    re-bonjour


    Tu crees normalement le 2eme storyboard ....et tu utlises l'event StoryBoard.Completed du 1er pour demarrer le 2 eme storyboard
    Tu dois supprimer repeatbehavior =forever dans le 1er sinon bien sur il n'a pas de fin....
    code behind.cs du form exemple:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    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.Media.Animation;
     
    namespace WpfAnimation
    {
        /// <summary>
        /// Logique d'interaction pour Window3.xaml
        /// </summary>
        public partial class Window3 : Window
        {
     
            private Storyboard sb1 = new Storyboard();
            private Storyboard sb2 = new Storyboard();
            public Window3()
            {
                InitializeComponent();
            }
     
            private void btn_Click(object sender, RoutedEventArgs e)
            {
     
                NameScope.SetNameScope(this, new NameScope());
     
                DoubleAnimationUsingKeyFrames da = new DoubleAnimationUsingKeyFrames();
                da.Duration = new Duration(new TimeSpan(0, 0, 2));
                DoubleKeyFrame dkf = new EasingDoubleKeyFrame(0, new TimeSpan(0, 0, 0));
                DoubleKeyFrame dkf1 = new EasingDoubleKeyFrame(50, new TimeSpan(0, 0, 2));
     
                da.KeyFrames.Add(dkf);
                da.KeyFrames.Add(dkf1);
     
     
                TranslateTransform tr = new TranslateTransform();
                this.RegisterName("myRectTranslate", tr);
                rect1.RenderTransform = tr;
     
     
     
                sb1.Completed += new EventHandler(sb1_Completed);
                sb1.Children.Add(da);
     
                Storyboard.SetTargetName(da, "myRectTranslate");
                Storyboard.SetTargetProperty(da, new PropertyPath(TranslateTransform.XProperty));
     
                sb1.Begin(rect1,true);
     
                //le 2 sb
                DoubleAnimation da2 = new DoubleAnimation();
                da2.From = 0;
                da2.To = 360;
                da2.Duration = new Duration(new TimeSpan(0, 0, 5));
     
     
                RotateTransform rot = new RotateTransform();
                this.RegisterName("myRectRotate", rot);
                rect2.RenderTransformOrigin = new Point(0.5, 0.5);
                rect2.RenderTransform = rot;
     
     
     
     
     
                sb2.Completed += new EventHandler(sb2_Completed);
                sb2.Children.Add(da2);
                Storyboard.SetTargetName(da2, "myRectRotate");
                Storyboard.SetTargetProperty(da2, new PropertyPath( RotateTransform.AngleProperty ));
     
     
     
     
            }
     
     
     
            void sb1_Completed(object sender, EventArgs e)
            {
                sb2.Begin(rect2);
     
            }
            void sb2_Completed(object sender, EventArgs e)
            {
                sb1.Begin(rect1);
            }
     
     
        }
    }
    De plus dans cet exemple comme on a perdu le forever ,j'en profites pour redemarrer le 1er ce qui crees une boucle indefinie...

  3. #3
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2015
    Messages
    7
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Algérie

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Enseignement

    Informations forums :
    Inscription : Avril 2015
    Messages : 7
    Points : 5
    Points
    5
    Par défaut
    Merci MABROUKI pour la deuxième fois,
    En fait votre rèponse sera très utile pour moi dans mon travaille, mais ma question était un peu différente :
    Je veut lancer une animation dans un code qui contient aussi d'autres instructions ( pas forcément des animations ), le problème c'est qu' à l'éxecution, les instructions qui viennent juste après str.Begin() vont être éxecutées en paralèlle avec l'animation, on veut attendre la fin de cette dernière avant que le reste du code soit traité.
    exemple : un programme qui ordonne un tableau non trié va permuter entre les cases du tableau, est d'un seul cout il devient trié, même si l'animation de permutation n'est pas encore finie.
    Merci pour vos aides et Salam.

  4. #4
    Expert confirmé
    Inscrit en
    Avril 2008
    Messages
    2 564
    Détails du profil
    Informations personnelles :
    Âge : 64

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 564
    Points : 4 441
    Points
    4 441
    Par défaut
    bonjour
    Si c'est un tri de tableau tu n'as qu'à le lancer dans l'event Completed...à la fin de l'animation...
    Si c'est autre chose ,il faut du code ,parce que dit comme ca ,ca n'est pas tres clair....
    bon code...

  5. #5
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2015
    Messages
    7
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Algérie

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Enseignement

    Informations forums :
    Inscription : Avril 2015
    Messages : 7
    Points : 5
    Points
    5
    Par défaut
    Bonjour ,
    Normalement c'est avec await ou sync ... ( j'ai pas compris comment les-utiliser )
    voici une méthode qui lance une animation mais avant de sortir de cette méthode je veut qu'elle attendre jusqu'à la fin de l'animation :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
     
     public void translate(Shape rect,Double from,Double to,int sd,int sf,Demonstration demo)
            {
                rect.Visibility = Visibility.Visible;
     
                NameScope.SetNameScope(demo, new NameScope());
     
                DoubleAnimationUsingKeyFrames da = new DoubleAnimationUsingKeyFrames();
                DoubleKeyFrame dkf = new EasingDoubleKeyFrame(from, new TimeSpan(0, 0, sd));
                DoubleKeyFrame dkf1 = new EasingDoubleKeyFrame(to, new TimeSpan(0,0,sf));
     
                da.KeyFrames.Add(dkf);
                da.KeyFrames.Add(dkf1);
     
                TranslateTransform tr = new TranslateTransform();
                demo.RegisterName("myRectTranslate", tr);
                rect.RenderTransform = tr;
     
                Storyboard sb = new Storyboard();
                sb.Children.Add(da);
     
                Storyboard.SetTargetName(da, "myRectTranslate");
                Storyboard.SetTargetProperty(da, new PropertyPath(TranslateTransform.XProperty));
                sb.Children.Add(da);
     
                sb.Begin(rect);
               // On lance une instruction de genre :
                await Task.Delay(300);
     
            }

  6. #6
    Expert confirmé
    Inscrit en
    Avril 2008
    Messages
    2 564
    Détails du profil
    Informations personnelles :
    Âge : 64

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 564
    Points : 4 441
    Points
    4 441
    Par défaut
    bonjour
    Bah si tu veux à tout prix utiliser la programmation Asynchrone base sur les Taches (les fameux TAP) il faut
    definir :
    - une methode de type Task precede du mot clé "aync"
    - le nom de la methode doit etre "nomdemethodeAsync" le suffixe Async etant acoller à la fin par exemple :CaculatPrixAsync ,CalculInteretAsync....etc

    - le button click doit etre precede aussi du mot clé "aync"...
    Ceci fait du handler du button un "handler asynchrone" c.à.d capable de mettre en pile le "Point" (instruction ou il a lance notre methode),d'executer un autre code (dowork1) et d'attendre avec le mot cle await ...
    Des que le resultat du await est disponible il reprend l'execution du code juste apres le "Point" ...(il commande un café a await ,s'occupe à autre chose (dans dowork1) et des que await l'avise ,il le sirote)...
    Si le resultat du await est satifaisant il execute un autre travail (dowork2) c.à.d si le café est bon)....
    -de plus ta methode TranslateDemo doit etre revu de facon à creer le storyboard et le renvoyer sans le demarrer,ce travail etant devolu à la methode de type Task cite ci.avant....
    bref voici le code behind .cs du form principal de demarrage:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
     
    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.Animation;
    using System.Windows.Media.Imaging;
    using System.Windows.Shapes;
     
    namespace WpfAnimation
    {
        /// <summary>
        /// Logique d'interaction pour WinAnimationAwait2.xaml
        /// </summary>
        public partial class WinAnimationAwait2 : Window
        {
            private Demonstration demo;
            public WinAnimationAwait2()
            {
                InitializeComponent();
            }
     
            private async  void btnStartTask_Click(object sender, RoutedEventArgs e)
            {
                demo = new Demonstration();
                demo.Show();
     
                Storyboard myStoryBoard = TranslateDemo(demo.rect1, 10, 120, 15, demo);
     
                Task t = MethodAsync(myStoryBoard, demo.rect1,15);
     
                // une autre facon d'appeler notre methode si on ne pas savoir si elle est Completed;
                // await   MethodAsync(myStoryBoard, demo.rect1);
     
     
                //ici on attend
                 await t;
     
     
                if (t.IsCompleted)
                {
                    this.lblMessage.Content = "storyboard completed...";
     
                    //ici on fait un autre  travail apres que storyboard soit termine...
                    DoOtherWork2();
                }
     
            }
            //La methode doit s'appeller MethodeAsync et non Method 
            async Task MethodAsync(Storyboard sb, Shape rect,int delay)
            {
                sb.Begin(rect);
     
                 //ici on fait un travail en attendant la fin du storyboard
                DoOtherWork1();
     
                await Task.Delay(TimeSpan.FromSeconds(delay ));
     
            }
     
     
            //TranslateDemo modifie pour renvoy un storyboard 
            public Storyboard TranslateDemo(Shape rect, Double from, Double to, double duration, Demonstration demo)
            {
     
                rect.Visibility = Visibility.Visible;
     
                NameScope.SetNameScope(demo, new NameScope());
     
     
     
                DoubleAnimation da = new DoubleAnimation();
                da.From = from;
                da.To = to;
                da.Duration = TimeSpan.FromSeconds(duration);
     
                TranslateTransform tr = new TranslateTransform();
                demo.RegisterName("myRectTranslate", tr);
                rect.RenderTransform = tr;
     
     
                Storyboard sb = new Storyboard();
                sb.Children.Add(da);
     
                Storyboard.SetTargetName(da, "myRectTranslate");
                Storyboard.SetTargetProperty(da, new PropertyPath(TranslateTransform.XProperty));
                sb.Children.Add(da);
     
     
     
                return sb;
     
     
            }
     
            private void DoOtherWork1()
            {
     
     
                this.lbWork1.Items.Clear();
                for (int i = 1; i < 10000; i++)
                {
                    this.lbWork1.Items.Add(i.ToString());
                }
     
            }
            private void DoOtherWork2()
            {
     
     
                this.lbWork2.Items.Clear();
                for (int i = 1; i < 100; i++)
                {
                    this.lbWork2.Items.Add("item" + i.ToString());
                }
     
            }
        }
    }
    et le code xaml du form principal de demarrage:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
     
    <Window x:Class="WpfAnimation.WinAnimationAwait2"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="WinAnimationAwait2" Height="300" Width="300">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="auto"></RowDefinition>
                <RowDefinition Height="*"></RowDefinition>
                <RowDefinition Height="*"></RowDefinition>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"></ColumnDefinition>
                <ColumnDefinition Width="150"></ColumnDefinition>
            </Grid.ColumnDefinitions> 
            <Button 
                x:Name="btnStartTask"  
                Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2"
                Content="StartTask" Click="btnStartTask_Click"/>
            <ListBox  
                x:Name="lbWork1"
                Grid.Row="1" Grid.Column="0" 
                Background="WhiteSmoke" 
                Foreground="Brown"
                HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
                >
            </ListBox>
            <ListBox  
                x:Name="lbWork2"
                Grid.Row="2" Grid.Column="0" 
                Background="WhiteSmoke"  
                Foreground="Maroon"
                HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
                >
            </ListBox>
            <Label 
                x:Name="lblMessage"
                Grid.Row="1" Grid.Column="1" Grid.RowSpan="2"
                FontSize="16"
                Foreground="Red"
                Background="Violet"  
                HorizontalContentAlignment="Center" VerticalContentAlignment="Center"
                Content="wait please....">
            </Label>
        </Grid>
    </Window>
    code xaml du form Demonstration inchange :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
     
     
    <Window x:Class="WpfAnimation.Demonstration"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="Demonstration" Height="300" Width="300">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition></RowDefinition>
                <RowDefinition></RowDefinition>
            </Grid.RowDefinitions>
            <StackPanel Grid.Row="0" Background="LightBlue" >
                <Rectangle x:Name="rect1" 
                           HorizontalAlignment="Left"
                           Fill="Red" Stroke="Black" Height="50" Width="120"></Rectangle>
            </StackPanel>
            <StackPanel Grid.Row="1" Background="LightGray" >
     
                <Rectangle x:Name="rect2" 
                           HorizontalAlignment="Left"
                           Fill="Blue"  Stroke="Black" Height="50" Width="120"></Rectangle>
            </StackPanel>
        </Grid>
    </Window>
    bon code....

  7. #7
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2015
    Messages
    7
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Algérie

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Enseignement

    Informations forums :
    Inscription : Avril 2015
    Messages : 7
    Points : 5
    Points
    5
    Par défaut
    Bonjour,
    C'est plus que parfait, merci.

  8. #8
    Expert confirmé
    Inscrit en
    Avril 2008
    Messages
    2 564
    Détails du profil
    Informations personnelles :
    Âge : 64

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 564
    Points : 4 441
    Points
    4 441
    Par défaut
    Re-bonjour

    Pour controller interactivement un storyboard cree dans le code il faut preciser le 2eme parameter Boolean dans l'appel de sa methode begin :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
     
           // Begins the storyboard. 
            private void beginButton_Clicked(object sender, RoutedEventArgs args)
            {
                // Specifying "true" as the second Begin parameter
                // makes this storyboard controllable.
                myStoryboard.Begin(rect, true);          
     
            }
    // Pauses the storyboard. 
            private void pauseButton_Clicked(object sender, RoutedEventArgs args)
            {
                 myStoryboard.Pause(rect);          
     
            }
     
    // Advances the storyboard to its fill period. 
            private void skipToFillButton_Clicked(object sender, RoutedEventArgs args)
            {
                 myStoryboard.SkipToFill(rect);          
     
            } 
     
            // Updates the storyboard's speed. 
            private void setSpeedRatioButton_Clicked(object sender, RoutedEventArgs args)
            {
                // Makes the storyboard progress three times as fast as normal.
                myStoryboard.SetSpeedRatio(rect, 3);          
     
            }           
     
            // Stops the storyboard. 
            private void stopButton_Clicked(object sender, RoutedEventArgs args)
            {
                 myStoryboard.Stop(rect);          
     
            }
    la variable "rect" du rectangle anime doit etre evidemment declare en portee du class pour etre accessible....
    bon code...

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [Animation] Comment exécuter du code à la fin d'une animation ?
    Par Finality dans le forum Windows Presentation Foundation
    Réponses: 3
    Dernier message: 12/10/2008, 12h44
  2. mettre mon application en attente
    Par MissTech dans le forum C++Builder
    Réponses: 3
    Dernier message: 17/05/2006, 18h43
  3. Réponses: 42
    Dernier message: 13/01/2006, 15h51
  4. Api Windows : Ou mettre le code de l'application.
    Par fab29000 dans le forum Windows
    Réponses: 2
    Dernier message: 06/10/2005, 10h03
  5. Mettre un code php dans une variable...
    Par kedare dans le forum Langage
    Réponses: 6
    Dernier message: 19/09/2005, 13h55

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo