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 Binding INotifyPropertyChanged


Sujet :

C#

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Futur Membre du Club
    Profil pro
    Inscrit en
    Mars 2013
    Messages
    5
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2013
    Messages : 5
    Par défaut C# WPF Binding INotifyPropertyChanged
    Bonjour,

    Je développe une application en C# qui utilise WPF pour obtenir les informations envoyées par une Wii Balance Board en utilisant une bibli spécifique biensûr (WiiMoteLib)
    La classe est faite, les variables définies, la connexion se fait bien, le graphique est complet...
    Les tests consoles sont également concluants.

    Mon problème c'est que je suis passé à l'étape de Binding des variables de ma classe pour une de mes pages XML (TextBlock) avec un INotify.. pour avoir mes variables en temps réel (Update quoi).

    Voici mon code complet des éléments où je taff en ce moment :
    Il y a quelques modifications non concluantes...

    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
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using WiimoteLib; //Ma bibliothèque pour la WiiBalanceBoard
    using System.Globalization;
    using System.ComponentModel;
    using System.Windows;
    using System.Windows.Threading;
     
    namespace WiiKinéApp
    {
        public class WiiBalance
        {
            private Wiimote bb = new Wiimote();
            public WiiBalance()
            {
                //Connecte la WiiBalanceBoard :
                bb.Connect();
                //Fixe la led frontale de la WiiBlanceBoard :
                bb.SetLEDs(1);
            }
     
            private InfoPoids monInfosPoids;
            public void Update()
            {
                //Appels :
                WiimoteState s = bb.WiimoteState;
                monInfosPoids = new InfoPoids();
     
                // Définition des variables:
                //Capteur haut gauche, valeur en newton(kg) :
                string cpHgauche = s.BalanceBoardState.SensorValuesKg.TopLeft.ToString();
                //Capteur haut droit, valeur en newton(kg) :
                string cpHdroit = s.BalanceBoardState.SensorValuesKg.TopRight.ToString();
                //Capteur bas gauche, valeur en newton(kg) :
                string cpBgauche = s.BalanceBoardState.SensorValuesKg.BottomLeft.ToString();
                //Capteur bas droit, valeur en newton(kg) :
                string cpBdroit = s.BalanceBoardState.SensorValuesKg.BottomRight.ToString();
     
                //Là je fais mes convertions pour mes calculs par la suite:
                float PHgauche = float.Parse(cpHgauche, CultureInfo.InvariantCulture.NumberFormat);
                float PHdroit = float.Parse(cpHdroit, CultureInfo.InvariantCulture.NumberFormat);
                float PBgauche = float.Parse(cpBgauche, CultureInfo.InvariantCulture.NumberFormat);
                float PBdroit = float.Parse(cpBdroit, CultureInfo.InvariantCulture.NumberFormat);
     
                //Ici je fais les calculs pour faire mes pourcentages:
                float centPcent = PHgauche + PHdroit + PBgauche + PBdroit;
                monInfosPoids.CPgauchePCENT = (PHgauche / centPcent) * 100;
                monInfosPoids.CPHdroitPCENT = (PHdroit / centPcent) * 100;
                monInfosPoids.CPBgauchePCENT = (PBgauche / centPcent) * 100;
                monInfosPoids.CPBdroitPCENT = (PBdroit / centPcent) * 100;
                //Poids total en Kg :
                monInfosPoids.PoidsTTL = s.BalanceBoardState.WeightKg.ToString();
                //Pour la batterie :
                monInfosPoids.Battery = s.Battery;
            }
        }
     
        //Ce que j'utiliserai vraiment au final:
        public class InfoPoids : INotifyPropertyChanged
        {
            public void Maj()
            {
                DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
                timer.Tick += timerTicked;
                timer.Interval = new TimeSpan(0, 0, 1);
                timer.Start();
            }
     
            private void timerTicked(object sender, EventArgs e)
            {
                //Si tu veux notifier le changement de toutes les propriétés :
                OnPropertyChanged(String.Empty);
            }
     
            public event PropertyChangedEventHandler PropertyChanged;
            protected void OnPropertyChanged(string propertyName)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
            }
     
            private float cpgauchePCENT;
            public float CPgauchePCENT
            {
                get
                {
                    return cpgauchePCENT;
                }
                set
                {
                    cpgauchePCENT = value;
                    this.OnPropertyChanged("CPgauchePCENT");
                }
            }
     
            private float cpHdroitPCENT;
            public float CPHdroitPCENT
            {
                get
                {
                    return cpHdroitPCENT;
                }
                set
                {
                    cpHdroitPCENT = value;
                    this.OnPropertyChanged("CPHdroitPCENT");
                }
            }
     
            private float cpBgauchePCENT;
            public float CPBgauchePCENT
            {
                get
                {
                    return cpBgauchePCENT;
                }
                set
                {
                    cpBgauchePCENT = value;
                    this.OnPropertyChanged("CPBgauchePCENT");
                }
            }
     
            private float cpBdroitPCENT;
            public float CPBdroitPCENT
            {
                get
                {
                    return cpBdroitPCENT;
                }
                set
                {
                    cpBdroitPCENT = value;
                    this.OnPropertyChanged("CPBdroitPCENT");
                }
            }
     
     
            private string poidsTTL;
            public string PoidsTTL
            {
                get
                {
                    return poidsTTL;
                }
                set
                {
                    poidsTTL = value;
                    this.OnPropertyChanged("PoidsTTL");
                }
            }
     
            private float battery;
            public float Battery
            {
                get
                {
                    return battery;
                }
                set
                {
                    battery = value;
                    this.OnPropertyChanged("Battery");
                }
            }
        }
    }
    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
    <UserControl
    	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"
    	mc:Ignorable="d"
        xmlns:local ="clr-namespace:WiiKinéApp"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
    	x:Class="WiiKinéApp.LoadGame"
        Loaded="Window_Loaded"
    	d:DesignWidth="640" d:DesignHeight="480" Width="800" Height="600">
     
             <Grid>   
                <TextBlock Height="40" HorizontalAlignment="Left" Margin="0,119,0,0" VerticalAlignment="Top" Width="800" Text="B A L A N C E" TextWrapping="Wrap" FontSize="21.333" TextAlignment="Center" />
                <Image Height="298" HorizontalAlignment="Left" Margin="116,175,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="561" Source="/WiiKinéApp;component/Images/WiiBb.png" />   
                <TextBlock HorizontalAlignment="Left" Margin="276,492,0,0" Name="textBlock1" Text="Vous pesez : " VerticalAlignment="Top" />
                <TextBlock HorizontalAlignment="Left" Margin="480,492,0,0" Name="textBlock2" Text="Kg" VerticalAlignment="Top" />
                <TextBlock Text="{Binding Path=PoidsTTL, UpdateSourceTrigger=PropertyChanged}" Margin="400,480,350,82" FontSize="20"/>
                <local:MenuModel Height="600" HorizontalAlignment="Left" x:Name="menuModel1" VerticalAlignment="Top" Width="800" />
            </Grid>
     
    </UserControl>
    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
    using System;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Ink;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;
    using System.Globalization;
    using System.Windows.Data;
     
    namespace WiiKinéApp
    {
        public partial class LoadGame : UserControl, ISwitchable
        {
            private InfoPoids myInfo;
            public LoadGame()
            {
                myInfo= new InfoPoids();
                this.DataContext = myInfo;
                // Required to initialize variables
                InitializeComponent();
            }
     
            private void Window_Loaded(object sender, System.Windows.RoutedEventArgs e)
            {
                myInfo.Maj();
            }
     
            #region ISwitchable Members
            public void UtilizeState(object state)
            {
                throw new NotImplementedException();
            }
            #endregion
        }
    }
    Je pense que j'ai mis ce qu'il fallait.
    Le problème c'est que mon Binding ne fonctionne pas, la valeur de ma variable ne s'affiche pas et n'est pas mise à jour...
    J'ai essayé énormément de choses déjà, j'ai passé environ 15h sur ce problème que je n'arrive vraiment pas à résoudre malgré tout ce que j'ai déjà lu.
    J'ai besoin de vos lumière, merci d'avance.

  2. #2
    Expert éminent Avatar de Pol63
    Homme Profil pro
    .NET / SQL SERVER
    Inscrit en
    Avril 2007
    Messages
    14 197
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Puy de Dôme (Auvergne)

    Informations professionnelles :
    Activité : .NET / SQL SERVER

    Informations forums :
    Inscription : Avril 2007
    Messages : 14 197
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    this.datacontext = new infospoids
    ok mais si c'est une autre instance d'infospoids qui est modifiée normal que l'interface ne voit pas le changement

    et dans ton code on ne sait pas d'où vient le infospoids de la classe wiibalance

    au passage ne pas coller une image du code mais le code en l'entourant de la balise code (bouton # sur l'éditeur de message)
    Cours complets, tutos et autres FAQ ici : C# - VB.NET

  3. #3
    Futur Membre du Club
    Profil pro
    Inscrit en
    Mars 2013
    Messages
    5
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2013
    Messages : 5
    Par défaut
    Bonjour,

    Merci pour ta réponse déjà.
    Le InfoPoids vient de WiiBalanceBoard.cs
    J'ai passé encore 5h dessus aujourd'hui et je n'arrive toujours pas à résoudre mon pb.

    Voici mon code complet des éléments où je taff en ce moment : VOIR EDIT MESSAGE PRECEDENT
    Il y a quelques modifications non concluantes...

  4. #4
    Expert éminent Avatar de Pol63
    Homme Profil pro
    .NET / SQL SERVER
    Inscrit en
    Avril 2007
    Messages
    14 197
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Puy de Dôme (Auvergne)

    Informations professionnelles :
    Activité : .NET / SQL SERVER

    Informations forums :
    Inscription : Avril 2007
    Messages : 14 197
    Par défaut
    oui donc c'est bien un problème de débutant qui met des new partout ^^

    lis quelques cours/tutos sur la poo avant d'aller plus loin je pense

    si tu instancies 2 chiens, et que sur le 2ème tu fais .aboyer, le 1er n’aboiera jamais ...
    Cours complets, tutos et autres FAQ ici : C# - VB.NET

  5. #5
    Futur Membre du Club
    Profil pro
    Inscrit en
    Mars 2013
    Messages
    5
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2013
    Messages : 5
    Par défaut
    Si tu parles de :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
         private void Window_Loaded(object sender, System.Windows.RoutedEventArgs e)
            {
                WiiBalance connexion = new WiiBalance();
                connexion.Update();
                InfoPoids info = new InfoPoids();
                info.Maj();
            }
    le
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
                WiiBalance connexion = new WiiBalance();
                connexion.Update();
    est en commentaire, c'était pour la connexion de la Balance Board et ça a été mis ailleurs.
    Oui je suis débutant mais là je ne vois vraiment pas où est le problème et des cours + articles j'en ai lu et en consulte encore plein, j'ai besoin d'une aide extérieur là...

    maintenant il y a seulement :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
            private void Window_Loaded(object sender, System.Windows.RoutedEventArgs e)
            {
                InfoPoids info = new InfoPoids();
                info.Maj();
            }
    Je n'arrive plus à avancer sur mon problème, j'ai besoin d'une personne qualifiée qui puisse m'aider réellement car par exemple j'arrive parfaitement à utiliser la notion de Binding et de INotifyPropertyChanged pour l'heure DateTime.Now par exemple... que j'ai placé dans mon application.

  6. #6
    Membre extrêmement actif
    Inscrit en
    Avril 2008
    Messages
    2 573
    Détails du profil
    Informations personnelles :
    Âge : 65

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 573
    Par défaut
    bonjour MONSTERru

    Pol63 a raison.....sur les news que tu seme un peu partout..
    Ensuite le usercontrol n'as d'appel à InitializeComponents....

    Tu devrais avoir simplement ceci:

    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
     
    public partial class LoadGame : UserControl, ISwitchable
        {
           //en porte globale svp 
           //pour le rendre accessible dans les differentes methode de ce class... 
            private InfoPoids myInfosPoids;  
     
            public LoadGame()
            {
                 //à deplacer ici avant InitializeComponents
                   myInfosPoids=new InfoPoids();
                   this.DataContext = myInfosPoids;
     
                // Required to initialize variables
                    InitializeComponents();  //A rajouter :c'est un control
     
     
              }
     
            private void Window_Loaded(object sender, System.Windows.RoutedEventArgs e)
            {
                 //soit ce code   (parce que declarer un new InfoPoids sans maj le DataContext c'est perdre binding)             
     
                 this.DataContext= new InfoPoids();
                 info.Maj();
     
                //soit ceci simplement
                 info.Maj();
            }
    bon code.........

Discussions similaires

  1. Réponses: 5
    Dernier message: 30/01/2008, 09h18
  2. [WPF] Binding et type custom
    Par sehshe dans le forum Framework .NET
    Réponses: 6
    Dernier message: 09/01/2008, 10h19
  3. wpf binding avec un dataset sans listbox
    Par ZashOne dans le forum Windows Presentation Foundation
    Réponses: 2
    Dernier message: 25/12/2007, 19h09
  4. [WPF][Binding] Comment binder un fichier XML sur un treeview?
    Par bakonu dans le forum Général Dotnet
    Réponses: 5
    Dernier message: 26/11/2007, 17h09
  5. [WPF] Binding sur app.config
    Par despeludo dans le forum Windows Presentation Foundation
    Réponses: 2
    Dernier message: 24/10/2007, 22h56

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