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

Silverlight Discussion :

Détecter le changement du texte dans un TextBlock


Sujet :

Silverlight

  1. #1
    Membre régulier Avatar de cyberbobby
    Inscrit en
    Février 2009
    Messages
    171
    Détails du profil
    Informations forums :
    Inscription : Février 2009
    Messages : 171
    Points : 106
    Points
    106
    Par défaut Détecter le changement du texte dans un TextBlock
    Bonjour,

    J'ai une application qui contient des TextBlocks bindés sur des propriétés. Je souhaiterais détecter, d'une manière ou d'une autre, lorsque le texte affiché par mon TextBlock change et ce via un événement dans la vue (pas dans ma propriété). Soit au niveau du textblock ou du binding ? Est-ce possible de le détecter ?

    Merci

  2. #2
    Expert éminent sénior
    Avatar de Skyounet
    Homme Profil pro
    Software Engineer
    Inscrit en
    Mars 2005
    Messages
    6 380
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : Etats-Unis

    Informations professionnelles :
    Activité : Software Engineer
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mars 2005
    Messages : 6 380
    Points : 13 380
    Points
    13 380
    Par défaut
    Citation Envoyé par cyberbobby Voir le message
    Bonjour,

    J'ai une application qui contient des TextBlocks bindés sur des propriétés. Je souhaiterais détecter, d'une manière ou d'une autre, lorsque le texte affiché par mon TextBlock change et ce via un événement dans la vue (pas dans ma propriété). Soit au niveau du textblock ou du binding ? Est-ce possible de le détecter ?

    Merci
    Ben dans ta vue tu t'abonnes au PropertyChanged de ton model et dans la callback tu regardes si c'est une des propriétés qui est bindé à tes TextBlocks.

  3. #3
    Membre régulier Avatar de cyberbobby
    Inscrit en
    Février 2009
    Messages
    171
    Détails du profil
    Informations forums :
    Inscription : Février 2009
    Messages : 171
    Points : 106
    Points
    106
    Par défaut
    Euh, un peu de code peut-être ?

    En fait, j'ai ma propriété dans un objet qui est dans mon VM.

    Genre :

    MonObjet.UnAutreObjet.Value;

    J'ai une prop vers MonObjet dans ma VM.

  4. #4
    Membre régulier Avatar de cyberbobby
    Inscrit en
    Février 2009
    Messages
    171
    Détails du profil
    Informations forums :
    Inscription : Février 2009
    Messages : 171
    Points : 106
    Points
    106
    Par défaut
    Euh ... Non ?

  5. #5
    Rédacteur
    Avatar de Nathanael Marchand
    Homme Profil pro
    Expert .Net So@t
    Inscrit en
    Octobre 2008
    Messages
    3 615
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Expert .Net So@t
    Secteur : Conseil

    Informations forums :
    Inscription : Octobre 2008
    Messages : 3 615
    Points : 8 082
    Points
    8 082
    Par défaut
    Il faut que le binding soit en Direction=TwoWay ou peut être ai-je mal compris la question?

  6. #6
    Membre régulier Avatar de cyberbobby
    Inscrit en
    Février 2009
    Messages
    171
    Détails du profil
    Informations forums :
    Inscription : Février 2009
    Messages : 171
    Points : 106
    Points
    106
    Par défaut
    Tu as sans doute mal compris

    Je parle ici d'un TextBlock.

    Lorsque son texte est rafraichi :

    ex, il affichait 2, puis affiche 5.

    J'aimerais avoir un événement qui me prévient que la valeur a changé. (équivalent tu TextChanged pour une TextBox)

  7. #7
    Rédacteur
    Avatar de Nathanael Marchand
    Homme Profil pro
    Expert .Net So@t
    Inscrit en
    Octobre 2008
    Messages
    3 615
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Expert .Net So@t
    Secteur : Conseil

    Informations forums :
    Inscription : Octobre 2008
    Messages : 3 615
    Points : 8 082
    Points
    8 082
    Par défaut
    Haaan voui! En effet, autant pour moi! J'avais lu TextBox

    Du coup effectivement c'est la solution de skyounet qui prime.
    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
     
    public class MyView
    {
    public MyView()
    {
    //TonConstructeur
     
    Loaded+=ViewLoaded;
    }
     
    public void ViewLoaded(object sender, EventArgs e)
    {
    var viewmodel = DataContext as MyViewModel;
    viewmodel.MyObjet.PropertyChanged+=MyTextChanged;
    }
     
    public void MyTextChanged(object sender, PropertyChangedEventArgs e)
    {
     if(e.Property =="MyFieldOnMyObject")
        //Mon traitement ici
    }
     
    }

  8. #8
    Membre émérite
    Avatar de Samuel Blanchard
    Homme Profil pro
    Expert .NET
    Inscrit en
    Février 2010
    Messages
    1 504
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 51
    Localisation : France

    Informations professionnelles :
    Activité : Expert .NET

    Informations forums :
    Inscription : Février 2010
    Messages : 1 504
    Points : 2 682
    Points
    2 682
    Par défaut
    Bonjour,

    Bien que la notification par VM soit la façon la plus simple et la plus élégante de détecter un changement, il peut être pratique parfois qu'une DependencyProperty d'un control (dont on a pas forcément le source) soit notifiable :

    Cette technique est issu de ce blog :

    http://agsmith.wordpress.com/2008/04...d-alternative/

    J'ai repris le code et l'ai légèrement modifié pour Silverlight :

    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
     
        public sealed class PropertyChangeNotifier :
        DependencyObject,
        IDisposable
        {
            #region Member Variables
            private WeakReference _propertySource;
            #endregion // Member Variables
     
            #region Constructor
            public PropertyChangeNotifier(DependencyObject propertySource, string path)
                : this(propertySource, new PropertyPath(path))
            {
            }
            public PropertyChangeNotifier(DependencyObject propertySource, DependencyProperty property)
                : this(propertySource, new PropertyPath(property))
            {
            }
            public PropertyChangeNotifier(DependencyObject propertySource, PropertyPath property)
            {
                if (null == propertySource)
                    throw new ArgumentNullException("propertySource");
                if (null == property)
                    throw new ArgumentNullException("property");
                this._propertySource = new WeakReference(propertySource);
                Binding binding = new Binding();
                binding.Path = property;
                binding.Mode = BindingMode.OneWay;
                binding.Source = propertySource;
                BindingOperations.SetBinding(this, ValueProperty, binding);
            }
            #endregion // Constructor
     
            #region PropertySource
            public DependencyObject PropertySource
            {
                get
                {
                    try
                    {
                        // note, it is possible that accessing the target property
                        // will result in an exception so i’ve wrapped this check
                        // in a try catch
                        return this._propertySource.IsAlive
                        ? this._propertySource.Target as DependencyObject
                        : null;
                    }
                    catch
                    {
                        return null;
                    }
                }
            }
            #endregion // PropertySource
     
            #region Value
            /// <summary>
            /// Identifies the <see cref=”Value”/> dependency property
            /// </summary>
            public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value",
            typeof(object), typeof(PropertyChangeNotifier), new PropertyMetadata(null, new PropertyChangedCallback(OnPropertyChanged)));
     
            private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
            {
                PropertyChangeNotifier notifier = (PropertyChangeNotifier)d;
                if (null != notifier.ValueChanged)
                    notifier.ValueChanged(notifier, EventArgs.Empty);
            }
     
            /// <summary>
            /// Returns/sets the value of the property
            /// </summary>
            /// <seealso cref=”ValueProperty”/>
            [Description("Returns/sets the value of the property")]
            [Category("Behavior")]
            //[Bindable(true)]
            public object Value
            {
                get
                {
                    return (object)this.GetValue(PropertyChangeNotifier.ValueProperty);
                }
                set
                {
                    this.SetValue(PropertyChangeNotifier.ValueProperty, value);
                }
            }
            #endregion //Value
     
            #region Events
            public event EventHandler ValueChanged;
            #endregion // Events
     
            #region IDisposable Members
            public void Dispose()
            {
                //BindingOperations.ClearBinding(this, ValueProperty);
            }
            #endregion
        }
    à utiliser c'est assez simple :

    en XAML :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
      <Grid x:Name="LayoutRoot">
            <TextBlock x:Name="TextBlock"></TextBlock>
      </Grid>
    en C# :

    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
     
        public partial class MainPage : UserControl
        {
            public MainPage()
            {
                InitializeComponent();
     
                PropertyChangeNotifier notifierText = new PropertyChangeNotifier(this.TextBlock, "Text");
                notifierText.ValueChanged += new EventHandler(TextValueChanged);
     
                this.TextBlock.Text = "Hello";
            }
     
            /// <summary>
            /// Changement de Text
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
     
            void TextValueChanged(object sender, EventArgs e)
            {
                  PropertyChangeNotifier notifier = sender as PropertyChangeNotifier;
                  string text = (string)notifier.Value;
            }
    Je n'ai pas utilisé cette technique en production donc pas possible de te donner les inconvénients celle ci (s'il y en a).

  9. #9
    Membre régulier Avatar de cyberbobby
    Inscrit en
    Février 2009
    Messages
    171
    Détails du profil
    Informations forums :
    Inscription : Février 2009
    Messages : 171
    Points : 106
    Points
    106
    Par défaut
    Wow ! Extra !

    J'avais commencé avec la première mais je garde la deuxième au chaud !

    Merci à tous les 3. ;-)

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

Discussions similaires

  1. Réponses: 1
    Dernier message: 16/12/2006, 16h45
  2. Réponses: 4
    Dernier message: 30/10/2006, 00h53
  3. changement de texte dans un champs static
    Par nbegorre dans le forum MFC
    Réponses: 3
    Dernier message: 29/06/2006, 23h33
  4. [MFC] changement de texte dans un bouton
    Par benjiprog dans le forum MFC
    Réponses: 16
    Dernier message: 12/06/2006, 20h48
  5. DÉBUDANT : Détecter la selection du text dans un Edit .
    Par LibrairieSI dans le forum Windows
    Réponses: 1
    Dernier message: 16/10/2005, 00h54

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