begin process at 2010 02 10 01:48:25
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

.NET

 > IMPLÉMENTER FACILEMENT INOTIFYPROPERTYCHANGED

IMPLÉMENTER FACILEMENT INOTIFYPROPERTYCHANGED


 Information sur la source

Note :
9 / 10 - par 1 personne
9,00 / 10

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10
Catégorie :.NET Source .NET ( DotNet ) Classé sous :PostSharp, INotifyPropertyChanged, OnFieldAccessAspect Niveau :Débutant Date de création :09/10/2007 Date de mise à jour :10/10/2007 12:36:21 Vu / téléchargé :4 515 / 72

Auteur : mathmax

Ecrire un message privé
Site perso
Commentaire sur cette source (4)
Ajouter un commentaire et/ou une note

 Description

Ce petit bout de code montre comment implémenter INotifyPropertyChanged en ajoutant seulement un attribut personnalisé. Je l'ai écrit en C# 3.0, bien que seul le framework 2.0 est nécessaire à cette implémentation. Attention, le projet est un projet VS 2008.

Source

  • using System;
  • using System.Collections.Generic;
  • using System.Linq;
  • using System.Text;
  • using System.ComponentModel;
  • using PostSharp.Laos;
  • using System.Text.RegularExpressions;
  • namespace ConsoleApplication1
  • {
  • class Program
  • {
  • static void Main(string[] args)
  • {
  • Test t = new Test();
  • t.PropertyChanged += new PropertyChangedEventHandler((s, e) =>
  • {
  • Console.WriteLine(string.Format("{0} has changed", e.PropertyName));
  • });
  • t.Prop1 = "a value";
  • t.Prop2 = "a value";
  • t.Prop3 = "a value";
  • }
  • }
  • [NotifyPropertyChanged]
  • public class Test : INotifyPropertyChanged
  • {
  • public string Prop1 { get; set; }
  • public string Prop2;
  • private string _Prop3;
  • public string Prop3
  • {
  • get { return _Prop3; }
  • set { _Prop3 = value; }
  • }
  • #region INotifyPropertyChanged Members
  • public event PropertyChangedEventHandler PropertyChanged;
  • #endregion
  • }
  • [Serializable]
  • public class NotifyPropertyChanged : OnFieldAccessAspect
  • {
  • public override void OnSetValue(FieldAccessEventArgs eventArgs)
  • {
  • base.OnSetValue(eventArgs);
  • var owner = eventArgs.Instance;
  • string propertyName = string.Empty;
  • string fieldName = eventArgs.FieldInfo.Name;
  • Regex reg = new Regex(@"(<)(\w*?)(>k__BackingField)");
  • Match match = reg.Match(fieldName);
  • if (match.Success)
  • propertyName = match.Groups[2].Value;
  • else if(fieldName.StartsWith("~"))
  • propertyName = fieldName.Replace("~", string.Empty);
  • else if(fieldName.StartsWith("_"))
  • propertyName = fieldName.Replace("_", string.Empty);
  • var e = new PropertyChangedEventArgs(propertyName);
  • FireEvent(owner, "PropertyChanged", e);
  • }
  • //http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=776014&SiteID=1
  • public void FireEvent(object owner, string name, EventArgs e)
  • {
  • MulticastDelegate eventDelagate =
  • (MulticastDelegate)owner.GetType().GetField(name,
  • System.Reflection.BindingFlags.Instance |
  • System.Reflection.BindingFlags.NonPublic).GetValue(owner);
  • if (eventDelagate != null)
  • {
  • Delegate[] delegates = eventDelagate.GetInvocationList();
  • foreach (Delegate dlg in delegates)
  • dlg.Method.Invoke(dlg.Target, new object[] { owner, e });
  • }
  • }
  • }
  • }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using PostSharp.Laos;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Test t = new Test();
            t.PropertyChanged += new PropertyChangedEventHandler((s, e) =>
            {
                Console.WriteLine(string.Format("{0} has changed", e.PropertyName));
            });

            t.Prop1 = "a value";
            t.Prop2 = "a value";
            t.Prop3 = "a value";
        }
    }

    [NotifyPropertyChanged]
    public class Test : INotifyPropertyChanged
    {
        public string Prop1 { get; set; }
        
        public string Prop2;

        private string _Prop3;

        public string Prop3
        {
            get { return _Prop3; }
            set { _Prop3 = value; }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
    }

    [Serializable]
    public class NotifyPropertyChanged : OnFieldAccessAspect
    {
        public override void OnSetValue(FieldAccessEventArgs eventArgs)
        {
            base.OnSetValue(eventArgs);
            
            var owner = eventArgs.Instance;

            string propertyName = string.Empty;
            string fieldName = eventArgs.FieldInfo.Name;
            Regex reg = new Regex(@"(<)(\w*?)(>k__BackingField)");
            Match match = reg.Match(fieldName);
            if (match.Success)
                propertyName = match.Groups[2].Value;
            else if(fieldName.StartsWith("~"))
                propertyName = fieldName.Replace("~", string.Empty);
            else if(fieldName.StartsWith("_"))
                propertyName = fieldName.Replace("_", string.Empty);

            var e = new PropertyChangedEventArgs(propertyName);

            FireEvent(owner, "PropertyChanged", e); 
        }

        //http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=776014&SiteID=1
        public void FireEvent(object owner, string name, EventArgs e)
        {
            MulticastDelegate eventDelagate =
                  (MulticastDelegate)owner.GetType().GetField(name,
                   System.Reflection.BindingFlags.Instance |
                   System.Reflection.BindingFlags.NonPublic).GetValue(owner);

            if (eventDelagate != null)
            {
                Delegate[] delegates = eventDelagate.GetInvocationList();

                foreach (Delegate dlg in delegates)
                    dlg.Method.Invoke(dlg.Target, new object[] { owner, e });
            }
        }    
    }
}

 Conclusion

Je me sert de PostSharp (http://www.postsharp.org/documentation/simple-tra ce-aspect-tutorial)
pour intercepter les "set" des propriétés.

 Fichier Zip

Les Membres Club peuvent télécharger directement un fichier contenu dans le zip sans télécharger le zip en entier !

Télécharger le zip


 Historique

09 octobre 2007 14:42:14 :
ajout d'une conclusion.
09 octobre 2007 20:52:07 :
précisions sur le type de projet et la spécification utilisée.
10 octobre 2007 12:36:21 :
correction code

 Sources du même auteur

Source avec Zip Source avec une capture Source .NET (Dotnet) BINDER DES PROPRIÉTÉS CALCULÉES AVEC WPF
Source avec Zip Source .NET (Dotnet) PROPRIÉTÉS D'EXTENSION AVEC C# 3.0

 Sources de la même categorie

Source avec Zip CHAT SERVER-CLIENT par abderrahmenbilog
Source avec Zip Source avec une capture Source .NET (Dotnet) SIMULATION DE CONSOLE POUR WINDOWS MOBILE par originalcompo
Source avec Zip Source .NET (Dotnet) BASE DE DONNÉES EN XML par DanMor498
Source avec Zip Source avec une capture Source .NET (Dotnet) SIMPLECONV - APPLICATION DE CONVERSION MONÉTAIRE AVEC TAUX E... par Jeffrey_
Source avec Zip Source .NET (Dotnet) TRAITEUR D'IMAGE (MINI) par ycyril

 Sources en rapport avec celle ci

Source avec Zip Source .NET (Dotnet) PROPRIÉTÉS D'EXTENSION AVEC C# 3.0 par mathmax

Commentaires et avis

Commentaire de sebmafate le 10/10/2007 09:01:57 administrateur CS

Remarque :
- à la ligne 60 : à quoi sert le String.Format ?

A part ça... bon code...

Commentaire de mathmax le 10/10/2007 10:33:23

A rien. Tu as raison :-).

Commentaire de UNi le 13/01/2008 11:22:41 9/10

Merci justement je cherché comment affecter un évement sur le changement d'un propriété ;)

Commentaire de mathmax le 13/01/2008 14:19:18

En fait, je me suis rendu compte après avoir fais cette source que quelque chose de mieux avait déjà été fait dans les samples de postsharp : http://doc.postsharp.org/index.html#http://doc.postsharp.org/UserGuide/Samples/Overview.html

 Ajouter un commentaire


Discussions en rapport avec ce code source dans le forum

INotifypropertychanged utilisation ? [ par GillouXman ] Salut tout le monde, j'ai une petite question qui me turlupine. Depuis WPF/Silverlight on parle bcp de binding et tout ca blablabla... et notamment d Besoin d'aide avec postsharp [ par teddyalbina ] Salut, J'ai un gros problème avec postsharp lorsque je l'utilise dans des assemblies X64. J'ai donc téléchargé le source et recompilé le tout en X64.


Nos sponsors


Sondage...

CalendriCode

Février 2010
LMMJVSD
1234567
891011121314
15161718192021
22232425262728

Consulter la suite du CalendriCode

 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 0,811 sec (4)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales