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

Windows Forms Discussion :

UserControl - Ajout de propriétés


Sujet :

Windows Forms

  1. #1
    Membre du Club
    Profil pro
    Inscrit en
    Août 2006
    Messages
    70
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Août 2006
    Messages : 70
    Points : 66
    Points
    66
    Par défaut UserControl - Ajout de propriétés
    Bonjour, j'aurais besoins de votre aide:

    je creer un composant (userControl)

    Nom : 2016-08-25_14h17_55.png
Affichages : 510
Taille : 91,8 Ko
    jusque la tout fonctionne bien.

    j'aimerais ajouter une "super propriété" comportant plusieurs propriété comme la propreté font par exemple ?
    Nom : 2016-08-25_14h20_08.png
Affichages : 358
Taille : 4,0 KoNom : 2016-08-25_14h20_40.png
Affichages : 377
Taille : 10,0 Ko


    j'ai essayé plusieurs méthode, sans succès.
    par avance merci pour votre aide, piste.

    Thierry

  2. #2
    Membre expert
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Octobre 2013
    Messages
    1 563
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2013
    Messages : 1 563
    Points : 3 404
    Points
    3 404
    Par défaut
    Bonjour,

    Pour ma part j'avais pu faire une propriété de type collection d'objet et ça fonctionnait bien. Par contre il me semble que je m'était cassé les dents sur la "super propriété"

    Après, pour te donner des pistes, il faut chercher autour du designer. Peut être que ce lien pourra t'aider.

  3. #3
    Membre du Club
    Profil pro
    Inscrit en
    Août 2006
    Messages
    70
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Août 2006
    Messages : 70
    Points : 66
    Points
    66
    Par défaut
    Merci pour ce liens.

    je suis sur une piste.

    soit créer une class , soit une structure avec 2 attributs par exemple X, Y de type int

    => a l"intérieur, surcharger la méthode ToString (celle ci est appelé quand on regarde la propriété du control..)

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     
                public override string ToString()
                {
                    return (String.Format("{0};{1}", x, y));
                }

    en haut de la class, il faut définir
    [TypeConverter(typeof(xxxxxConverter))]


    puis, définir la méthode de convertion de type: xxxxConverter.
    infos disponible ici: https://msdn.microsoft.com/fr-fr/lib...v=vs.120).aspx


    Si il y a des intéresser, J'essaye de mettre un bout de code au propre... sur ce post... mais ca serait intéressant de compléter le beau tutoriaux c# sur les UserControls.
    si pas d'intéresser, je passerais le post en résolu.

    Merci

  4. #4
    Membre expert
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Octobre 2013
    Messages
    1 563
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2013
    Messages : 1 563
    Points : 3 404
    Points
    3 404
    Par défaut
    Citation Envoyé par mastronic Voir le message
    Si il y a des intéresser, J'essaye de mettre un bout de code au propre... sur ce post... mais ca serait intéressant de compléter le beau tutoriaux c# sur les UserControls.
    si pas d'intéresser, je passerais le post en résolu.
    Moi je suis intéressé

    Merci par avance !

  5. #5
    Membre du Club
    Profil pro
    Inscrit en
    Août 2006
    Messages
    70
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Août 2006
    Messages : 70
    Points : 66
    Points
    66
    Par défaut
    Sous VS2005 (Framework 2.0) le projet compile sans avertissement.
    Au lancement du Control, l'attribut qui référence 3 attributs ne s'affiche pas correctement (bloc noir) quand on clique ca génère un message alertant sur une exception non gérer ( sans m'indiquer la ligne du code concerner... )


    je reprend le projet et l'ouvre depuis VS2015 Express => indique d'utilisé Framework 2.0 ..et surprise le Control fonctionne.


    Détails: copie écran, a gauche VS2005 , a droite VS2015

    Nom : vs2005-vs2015-userControls.png
Affichages : 499
Taille : 129,6 Ko


    détails:
    L'exception System.NullReferenceException n'a pas été gérée
    Message="La référence d'objet n'est pas définie à une instance d'un objet."
    Source="mscorlib"
    StackTrace:
    à System.RuntimeTypeHandle._GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, Boolean loadTypeFromPartialName)
    à System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark)
    à System.RuntimeType.PrivateGetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark)
    à System.Type.GetType(String typeName)
    à System.ComponentModel.PropertyDescriptor.GetTypeFromName(String typeName)
    à System.ComponentModel.PropertyDescriptor.get_Converter()
    à System.Windows.Forms.PropertyGridInternal.PropertyDescriptorGridEntry.get_TypeConverter()
    à System.Windows.Forms.PropertyGridInternal.GridEntry.GetPropertyTextValue(Object value)
    à System.Windows.Forms.PropertyGridInternal.PropertyGridView.SelectRow(Int32 row)
    à System.Windows.Forms.PropertyGridInternal.PropertyGridView.SelectGridEntry(GridEntry gridEntry, Boolean fPageIn)
    à System.Windows.Forms.PropertyGridInternal.PropertyGridView.OnGridEntryValueClick(Object s, EventArgs e)
    à System.Windows.Forms.PropertyGridInternal.GridEntry.RaiseEvent(Object key, EventArgs e)
    à System.Windows.Forms.PropertyGridInternal.GridEntry.OnMouseClick(Int32 x, Int32 y, Int32 count, MouseButtons button)
    à System.Windows.Forms.PropertyGridInternal.PropertyGridView.OnMouseDown(MouseEventArgs me)
    à System.Windows.Forms.Control.WmMouseDown(Message& m, MouseButtons button, Int32 clicks)
    à System.Windows.Forms.Control.WndProc(Message& m)
    à System.Windows.Forms.PropertyGridInternal.PropertyGridView.WndProc(Message& m)
    à System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
    à System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
    à System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
    à System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
    à System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
    à System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
    à Microsoft.VisualStudio.Tools.UserControlTestContainer.Main(String[] args)


    Avez vous eu se genre de désagrément ?

    comme indiquer dans le post précédant, je n'oublie pas de mettre un exemple de code avec quelques explications. je ferais prochainement ZenZiTone

    Thierry

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

    Informations professionnelles :
    Activité : .NET / SQL SERVER

    Informations forums :
    Inscription : Avril 2007
    Messages : 14 147
    Points : 25 054
    Points
    25 054
    Par défaut
    lu en diagonale, mais pour que le property grid des propriétés de visual studio te permette d'inspecter tout l'objet il faut :
    - une propriété typée sur une classe avec toutes les sous propriétés
    - un attribut au dessus de la "super" propriété system.componentmodel.designerserializationvisibility(content)

    cet attribut à pour effet que le designer va enregistrer dans le .designer.cs le code qui instancie la propriété et remplit ses sous propriétés
    Cours complets, tutos et autres FAQ ici : C# - VB.NET

  7. #7
    Membre du Club
    Profil pro
    Inscrit en
    Août 2006
    Messages
    70
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Août 2006
    Messages : 70
    Points : 66
    Points
    66
    Par défaut source qui fonctionne :)
    Comme promis, Voici un exemple de code sous VS2015 Express ( Framework cible 2.0)

    Nom : 2016-09-05_10h37_15.png
Affichages : 346
Taille : 55,9 Ko

    Dans la class ou vous gérez le control:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
            [Category("Configuration"), Browsable(true), Description("Indicateur N°1")]
            public IndicatorProperty Indicator
            {
                get { return indicator; }
                set
                {
                    indicator = value;
                    pbox.Refresh();
                }
            }

    Fichier IndicatorProperty.cs:
    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
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
     
    using System;
    using System.Collections;
    using System.Globalization;
    using System.Reflection;
    using System.Runtime.InteropServices;
     
    using System.ComponentModel;
    using System.ComponentModel.Design.Serialization;
    using System.Drawing;
     
     
    using System.Text.RegularExpressions;
     
    namespace ThermometerControl
    {
       // [Serializable()]
        [TypeConverter(typeof(SensorIndicatorConverter))]
        public struct IndicatorProperty
        {
            float _value;
            Color _color;
            string _label;
     
            public IndicatorProperty(string label, Color color, float value)
                : this()
            {
                _value = value;
                _color = color;
                _label = label;
            }
            /// <summary>
            /// instance utilisé lors d'une modifications des attributs sous format texte.
            /// </summary>
            /// <param name="str">Chaine modifiée dans "property grid" pour l'enssemble des attributs de "Indicator" à décoder</param>
            public IndicatorProperty(string str)
            {
                _value = 0;
                _color = Color.Black;
                _label = "";
     
                if (string.IsNullOrEmpty(str)) throw new ArgumentNullException();
     
                /* decode le string, pour déterminer les valeurs */
                string[] attributs = str.Split(';');
                /* control des valeurs */
                if (attributs.Length == 3)
                {
                    try
                    {
                        _label = attributs[0];
                        _color = extracColor(attributs[1]);
                        _value = float.Parse(attributs[2]);
                    }
                    catch(Exception ex)
                    {
                        throw new Exception("Init ThermometerIndicator: erreur value, " + ex.Message);
                      //  MessageBox.Show("Init ThermometerIndicator: erreur value, " + ex.Message);
                    }
                }
                else throw new Exception("Init ThermometerIndicator: erreur value");
            }
     
            /// <summary>
            /// Chaine afficher dans "property grid" pour l'enssemble des attributs de "Indicator"
            /// </summary>
            /// <returns></returns>
            public override string ToString()
            {
                return _label + ";" + _color.ToString() + ";" + _value.ToString();
            }
     
            public float Value
            {
                get { return _value; }
                set { _value = value; }
            }
     
            public Color Color
            {
                get { return _color; }
                set { _color = value; }
            }
     
            public String Label
            {
                get { return _label; }
                set { _label = value; }
            }
     
     
            /// <summary>
            /// Extrait la couleur d'une chaine ex:  "Color [xxx]"  (Avec xxx la couleur ex:  "Color [Red]")
            /// </summary>
            /// <param name="str">chaine comprenant la couleur</param>
            /// <returns>object Color</returns>
            private Color extracColor(String str)
            {
                string pattern = @"^(Color \[)(.*)(\])$";
                //string strInput = "Color [Red]";
                string strColor;
                Color color = Color.Empty;
     
                try
                {
                    Match match = Regex.Match(str, pattern, RegexOptions.IgnoreCase);
     
                    if (match.Success && match.Groups.Count == 4)
                    {
                        strColor = match.Groups[2].Value;
                        color = Color.FromName(strColor);
                    }
                }
                catch (Exception)
                {
                }
                return color;
            }
     
     
        }
     
        //Converter for define behavior on property grid
        public class SensorIndicatorConverter : TypeConverter
        {
            public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
            {
                if (sourceType == typeof(string))
                {
                    return true;
                }
                return base.CanConvertFrom(context, sourceType);
            }
     
            public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
            {
                if (destinationType == typeof(InstanceDescriptor))
                {
                    return true;
                }
                return base.CanConvertTo(context, destinationType);
            }
     
            public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
            {
                string strValue = value as string;
     
                if (strValue != null)
                {
                    return new IndicatorProperty(strValue);
                }
     
                return base.ConvertFrom(context, culture, value);
            }
     
            /// <summary>
            /// Demande de Convertion des propriétées dans "property grid" de la propriété typée avec toutes les sous propriétés (Super Propriétée)
            /// </summary>
            /// <param name="context"></param>
            /// <param name="culture"></param>
            /// <param name="value"></param>
            /// <param name="destinationType"></param>
            /// <returns></returns>
            public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
            {
                if (destinationType == null)
                {
                    throw new ArgumentNullException("destinationType");
                }
     
                if (value is IndicatorProperty)
                {
                    if (destinationType == typeof(string))
                    {
                        IndicatorProperty ThermometerIndicator = (IndicatorProperty)value;
                        return ThermometerIndicator.ToString();
                    }
                    if (destinationType == typeof(InstanceDescriptor))
                    {
                        IndicatorProperty ThermometerIndicator = (IndicatorProperty)value;
     
                        ConstructorInfo ctor = typeof(IndicatorProperty).GetConstructor(new Type[] { typeof(string), typeof(Color), typeof(float) });
                        if (ctor != null)
                        {
                            return new InstanceDescriptor(ctor, new object[] { ThermometerIndicator.Label, ThermometerIndicator.Color, ThermometerIndicator.Value });
                        }
                    }
                }
     
                return base.ConvertTo(context, culture, value, destinationType);
            }
     
     
            public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues)
            {
                if (propertyValues == null)
                {
                    throw new ArgumentNullException("propertyValues");
                }
     
                object label = propertyValues["Label"];
                object color = propertyValues["Color"];
                object value = propertyValues["Value"];
     
     
                if (label == null || color == null || value == null || !(label is string) || !(color is Color) || !(value is float))
                {
                    return null;
                    // throw new ArgumentException("values is not valid");
                }
                return new IndicatorProperty((string)label, (Color)color, (float)value);
            }
     
            public override bool GetCreateInstanceSupported(ITypeDescriptorContext context)
            {
                return true;
            }
     
            public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
            {
                PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(IndicatorProperty), attributes);
                return props.Sort(new string[] { "Label", "Color" ,"Value"});
            }
     
            public override bool GetPropertiesSupported(ITypeDescriptorContext context)
            {
                return true;
            }
        }
    }

  8. #8
    Membre du Club
    Profil pro
    Inscrit en
    Août 2006
    Messages
    70
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Août 2006
    Messages : 70
    Points : 66
    Points
    66
    Par défaut
    Citation Envoyé par ZenZiTone Voir le message
    Bonjour,

    Pour ma part j'avais pu faire une propriété de type collection d'objet et ça fonctionnait bien. Par contre il me semble que je m'était cassé les dents sur la "super propriété"
    comme promis , j'ai mis la source d’exemple sur le post ci dessus.
    tu indiquais collection d'objet... j'ai aussi essayer avec l'objet Dictionary mais on ne peux pas ajouter d'enregistrements , ni modifier ceux existants. Tu as déjà réussis avec un Dictionary ?
    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
     
            [Category("Configuration"), Browsable(true), Description("Ruban sur la Graduation")]
            public Dictionary<int, int> DictionaryTest
            {
                // indicatorRuban
                get
                {
                    return this.dictionaryTest;
                }
                set
                {
                    this.dictionaryTest = value;
                    pbox.Refresh();
                }
            }
    Ici l'attribut Distionnary test:
    Nom : 2016-09-05_10h49_33.png
Affichages : 355
Taille : 61,3 Ko

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

Discussions similaires

  1. [c#/UserControl] Ajout des nouvelles propriétés
    Par layouni dans le forum Windows Forms
    Réponses: 2
    Dernier message: 16/04/2007, 11h02
  2. Réponses: 1
    Dernier message: 28/03/2007, 16h12
  3. ajouter une propriété name
    Par butch dans le forum Delphi
    Réponses: 6
    Dernier message: 16/05/2006, 18h18
  4. [D6] PB ajout de propriétés font dans un composant
    Par Pill_S dans le forum Composants VCL
    Réponses: 11
    Dernier message: 25/10/2005, 21h16
  5. [active X] ajouter une propriété
    Par Blo0d4x3 dans le forum MFC
    Réponses: 4
    Dernier message: 22/09/2004, 10h47

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