Accueil > > > IMPLÉMENTER FACILEMENT INOTIFYPROPERTYCHANGED
IMPLÉMENTER FACILEMENT INOTIFYPROPERTYCHANGED
Information sur la source
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.
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
Sources de la même categorie
Commentaires et avis
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.
|
Derniers Blogs
UNE JOLIE-HORLOGE ET PAS QU'UN PEU !UNE JOLIE-HORLOGE ET PAS QU'UN PEU ! par neodante
Pour les possesseurs d'iPhone, ça y est Bijin Tokei - qui se traduit littéralement en Français par " Jolie Horloge " - est arrivé et GRATUITEMENT s'il vous plaît ! Après la version Tokyo, Hokkaido, night club, racing, Gal, "pour les mademoiselles'", . voi...
Cliquez pour lire la suite de l'article par neodante TECHDAYS PARIS 2010 : CONNECTEZ VOS DONNéES à SHAREPOINT 2010 AVEC LES BUSINESS CONNECTIVITY SERVICESTECHDAYS PARIS 2010 : CONNECTEZ VOS DONNéES à SHAREPOINT 2010 AVEC LES BUSINESS CONNECTIVITY SERVICES par ROMELARD Fabrice
Animé par: Gaetan Bouveret et Julien Chomarat Business Connectivity Services (BCS) est dans SharePoint 2010 la version 2 de Business Data Catalog (BDC dans SharePoint 2007). Il s'agit de la solution permettant de visualiser des données provenan...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice [DIVERS] SUIVRE VOS SéRIES PRéFéRéS SUR LA TOILE[DIVERS] SUIVRE VOS SéRIES PRéFéRéS SUR LA TOILE par orion
Comme de nombreux geek, je suis un grand amateur de série TV et je rate régulièrement des épisodes de mes séries préférés. Une solution s'offre à vous avec ce merveilleux site : Tv Gorge - www.tvgorge.com Moteur de recherche à l'appui, vous pouvez ...
Cliquez pour lire la suite de l'article par orion TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010 par ROMELARD Fabrice
Animé par: Vincent Bellet et Baptiste Giraudier La BI dans SharePoint 2010, Les nouveaux services d'application dans SP2010 et SQL Server Reporting services 2008 R2. La BI dans SharePoint est généralisée pour tous afin de permettre à tous les coll...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice
Logiciels
DB-MAIN (9.1.0)DB-MAIN (9.1.0)DB-MAIN is a data-modeling and data-architecture tool. It is designed to help developers and anal... Cliquez pour télécharger DB-MAIN Xilisoft DPG Convertisseur (5.1.37.0120)XILISOFT DPG CONVERTISSEUR (5.1.37.0120)Xilisoft DPG Convertisseur offre aux fans de Nintendo DS une bonne solution leur permettant de dé... Cliquez pour télécharger Xilisoft DPG Convertisseur GraphicsGale (2.01.01)GRAPHICSGALE (2.01.01)GraphicsGale est un logiciel de PixelArt avec de nombreuse fonctionnalités permettant de réalisé ... Cliquez pour télécharger GraphicsGale Architecte 3D (Platinum 2010)ARCHITECTE 3D (PLATINUM 2010)Architecte 3D Platinium vous permet de concevoir facilement les plans votre future maison, de l'é... Cliquez pour télécharger Architecte 3D TeamViewer 5 (TeamViewer 5)TEAMVIEWER 5 (TEAMVIEWER 5)Dépanner un ami,expliquer une manipulation devient un jeu d'enfant.
Prise en main d'un autre ord... Cliquez pour télécharger TeamViewer 5
|