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 :

IDictionary et binding bidirectionel


Sujet :

C#

  1. #1
    maa
    maa est déconnecté
    Membre éclairé
    Avatar de maa
    Inscrit en
    Octobre 2005
    Messages
    672
    Détails du profil
    Informations personnelles :
    Âge : 41

    Informations forums :
    Inscription : Octobre 2005
    Messages : 672
    Par défaut IDictionary et binding bidirectionel
    Bonjour,

    J'aimerais binder une SortedList<int, string> (ou une classe dérivée) à une combobox de manière à ce que les valeurs de ma SortedList soient affiché dans la combox dans l'ordre des clés. Il faudrait également que tout changement effectué dans ma SortedList soit répercuté automatiquement dans ma combobox.
    Auriez-vous une idée pour concrétiser cela ?

  2. #2
    Membre Expert
    Avatar de Mehdi Feki
    Profil pro
    Inscrit en
    Décembre 2004
    Messages
    1 113
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France

    Informations forums :
    Inscription : Décembre 2004
    Messages : 1 113
    Par défaut
    Salut,

    Je pense que ça ne marchera pas avec le BindingSource parce qu'il faut remettre à jour la DataSource lors du changement de la dictionary.

    Regarde de coté de l'Interface INotifyPropertyChanged, peut être que tu trouvera ton bonheure

  3. #3
    maa
    maa est déconnecté
    Membre éclairé
    Avatar de maa
    Inscrit en
    Octobre 2005
    Messages
    672
    Détails du profil
    Informations personnelles :
    Âge : 41

    Informations forums :
    Inscription : Octobre 2005
    Messages : 672
    Par défaut
    Implémenter INotifyPropertyChanged ne suffit pas pour que mon contrôle soit automatiquement mis à jour quand la datasource change. Il faut implémenter IBindingList.

    Cependant, j'ai put écrire 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
    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
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
     
        public interface INotifyList<T> : INotifyCollectionChanged, IList<T> { }
     
        public class NotifySource<T> : ITypedList, IBindingList
        {
            protected INotifyList<T> dataSource = null;
     
            private INotifyList<T> internalList;
     
            public INotifyList<T> InternalList
            {
                get { return internalList; }
                set
                {
                    internalList = value;
                    internalList.CollectionChanged += new NotifyCollectionChangedEventHandler(internalList_CollectionChanged);
                }
            }
     
            void internalList_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
            {
                if (ListChanged != null)
                {
                    ListChangedType t;
                    if(e.NewItems.Count!=0)
                        t = ListChangedType.ItemAdded;
                    else if (e.OldItems.Count!=0)
                        t = ListChangedType.ItemDeleted;
                    else if (e.OldStartingIndex != e.NewStartingIndex)
                        t = ListChangedType.ItemMoved;
                    else
                        t = ListChangedType.ItemChanged;
                    ListChanged(this, new ListChangedEventArgs(t,e.NewStartingIndex, e.OldStartingIndex));
                }
            }
     
            protected virtual IBindingList List
            {
                get
                {
                    if (InternalList == null)
                        InternalList = ((INotifyList<T>)ListBindingHelper.GetList(dataSource));
                    return new System.ComponentModel.BindingList<T>((IList<T>)InternalList);
                }
            }
     
            public INotifyList<T> DataSource
            {
                get { return dataSource; }
                set
                {
                    dataSource = value;
                    if (customSourceView != null)
                        customSourceView.ResetList();
                }
            }
     
            protected CustomSourceViewBase customSourceView = null;
     
            #region IBindingList Members
     
            public void AddIndex(PropertyDescriptor property)
            {
                List.AddIndex(property);
            }
     
            public object AddNew()
            {
                return List.AddNew();
            }
     
            public bool AllowEdit
            {
                get { return List.AllowEdit; }
            }
     
            public bool AllowNew
            {
                get { return List.AllowNew; }
            }
     
            public bool AllowRemove
            {
                get { return List.AllowRemove; }
            }
     
            public void ApplySort(PropertyDescriptor property, ListSortDirection direction)
            {
                List.ApplySort(property, direction);
            }
     
            public int Find(PropertyDescriptor property, object key)
            {
                return List.Find(property, key);
            }
     
            public bool IsSorted
            {
                get { return List.IsSorted; }
            }
     
            public event ListChangedEventHandler ListChanged;
     
            public void RemoveIndex(PropertyDescriptor property)
            {
                List.RemoveIndex(property);
            }
     
            public void RemoveSort()
            {
                List.RemoveSort();
            }
     
            public ListSortDirection SortDirection
            {
                get { return List.SortDirection; }
            }
     
            public PropertyDescriptor SortProperty
            {
                get { return List.SortProperty; }
            }
     
            public bool SupportsChangeNotification
            {
                get { return List.SupportsChangeNotification; }
            }
     
            public bool SupportsSearching
            {
                get { return List.SupportsSearching; }
            }
     
            public bool SupportsSorting
            {
                get { return List.SupportsSorting; }
            }
     
            #endregion
     
            #region ICollection Members
     
            public void CopyTo(Array array, int index)
            {
                List.CopyTo(array, index);
            }
     
            public bool IsSynchronized
            {
                get { return List.IsSynchronized; }
            }
     
            public object SyncRoot
            {
                get { return List.SyncRoot; }
            }
     
            public int Count
            {
                get { return List.Count; }
            }
     
            #endregion
     
            #region IList Members
     
            public int Add(object value)
            {
                return List.Add(value);
            }
     
            public void Clear()
            {
                List.Clear();
            }
     
            public bool Contains(object value)
            {
                return List.Contains(value);
            }
     
            public int IndexOf(object value)
            {
                return List.IndexOf(value);
            }
     
            public void Insert(int index, object value)
            {
                List.Insert(index, value);
            }
     
            public bool IsFixedSize
            {
                get { return List.IsFixedSize; }
            }
     
            public bool IsReadOnly
            {
                get { return List.IsReadOnly; }
            }
     
            public void Remove(object value)
            {
                List.Remove(value);
            }
     
            public void RemoveAt(int index)
            {
                List.RemoveAt(index);
            }
     
            public object this[int index]
            {
                get
                {
                    return List[index];
                }
                set
                {
                    List[index] = value;
                }
            }
     
            #endregion
     
            #region IEnumerable Members
     
            public IEnumerator GetEnumerator()
            {
                return List.GetEnumerator();
            }
     
            #endregion
     
            #region ITypedList Members
     
            public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors)
            {
                PropertyDescriptorCollection sourceProps;
                if (dataSource == null)
                    sourceProps = PropertyDescriptorCollection.Empty;
     
                object obj1 = ListBindingHelper.GetList(this.dataSource);
                sourceProps = ListBindingHelper.GetListItemProperties(obj1, listAccessors);
     
                return sourceProps;
            }
     
            public string GetListName(PropertyDescriptor[] listAccessors)
            {
                object obj1 = ListBindingHelper.GetList(this.dataSource);
                return ListBindingHelper.GetListName(obj1, listAccessors);
            }
     
            #endregion
        }
    En intercalant NotifySource<T> entre la datasource de mon contrôle et ma liste implémentant INotifyList<T>, le contrôle sera alors automatiquement mis à jour lorsque cette dernière changera.

    Maintenant il me reste à faire en gros la même chose mais pour les dictionary...

  4. #4
    maa
    maa est déconnecté
    Membre éclairé
    Avatar de maa
    Inscrit en
    Octobre 2005
    Messages
    672
    Détails du profil
    Informations personnelles :
    Âge : 41

    Informations forums :
    Inscription : Octobre 2005
    Messages : 672
    Par défaut
    J'ai réussi.

    Voici comment j'ai fait (si ça intéresse quelqu'un) :

    - Tout d'abord j'ai crée l'interface suivante :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
        public interface INotifyListSource<T> : INotifyCollectionChanged, IListSource<T> { }
        public interface IListSource<T>
        {
            bool ContainsListCollection { get; }
            IList<T> GetList();
        }
    - J'ai ensuite dérivé SortedList<TKey, TValue> en implémentant INotifyListSource<T> :

    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
     
        public class CsutomSortedList<TKey, TValue> : SortedList<TKey, TValue>, INotifyListSource<TValue>
        {
            private KeyValuePair<TKey, TValue> GetPair(TKey key)
            {
                foreach (KeyValuePair<TKey, TValue> pair in this)
                    if (pair.Key.Equals(key))
                        return pair;
                return new KeyValuePair<TKey,TValue>(key, default(TValue));
            }
     
            public new void Add(TKey key, TValue value)
            {
                base.Add(key, value);
                this.OnItemAdded(GetPair(key));
            }
     
            public new void Clear()
            {
                base.Clear();
                this.OnCollectionReset();
            }
     
            public new bool Remove(TKey key)
            {
                int index = this.IndexOfKey(key);
     
                bool result = base.Remove(key);
                this.OnItemRemoved(GetPair(key), index);
     
                return result;
            }
     
            public new void RemoveAt(int index)
            {
                var item = GetPair(Keys[index]);
                base.RemoveAt(index);
                this.OnItemRemoved(item, index);
            }
     
     
            #region INotifyCollectionChanged Members
     
            public event NotifyCollectionChangedEventHandler CollectionChanged;
     
            /// <summary>
            /// Fires the <see cref="CollectionChanged"/> event to indicate an item has been 
            /// added to the end of the collection.
            /// </summary>
            /// <param name="item">Item added to the collection.</param>
            protected void OnItemAdded(KeyValuePair<TKey, TValue> item)
            {
                if (this.CollectionChanged != null)
                {
                    this.CollectionChanged(this, new NotifyCollectionChangedEventArgs(
                        NotifyCollectionChangedAction.Add, item, this.Count - 1));
                }
            }
     
            /// <summary>
            /// Fires the <see cref="CollectionChanged"/> event to indicate the collection 
            /// has been reset.  This is used when the collection has been cleared or 
            /// entirely replaced.
            /// </summary>
            protected void OnCollectionReset()
            {
                if (this.CollectionChanged != null)
                {
                    this.CollectionChanged(this, new NotifyCollectionChangedEventArgs(
                        NotifyCollectionChangedAction.Reset));
                }
            }
     
            /// <summary>
            /// Fires the <see cref="CollectionChanged"/> event to indicate an item has 
            /// been inserted into the collection at the specified index.
            /// </summary>
            /// <param name="index">Index the item has been inserted at.</param>
            /// <param name="item">Item inserted into the collection.</param>
            protected void OnItemInserted(int index, KeyValuePair<TKey, TValue> item)
            {
                if (this.CollectionChanged != null)
                {
                    this.CollectionChanged(this, new NotifyCollectionChangedEventArgs(
                        NotifyCollectionChangedAction.Add, item, index));
                }
            }
     
            /// <summary>
            /// Fires the <see cref="CollectionChanged"/> event to indicate an item has
            /// been removed from the collection at the specified index.
            /// </summary>
            /// <param name="item">Item removed from the collection.</param>
            /// <param name="index">Index the item has been removed from.</param>
            protected void OnItemRemoved(KeyValuePair<TKey, TValue> item, int index)
            {
                if (this.CollectionChanged != null)
                {
                    this.CollectionChanged(this, new NotifyCollectionChangedEventArgs(
                        NotifyCollectionChangedAction.Remove, item, index));
                }
            }
            #endregion
     
            #region IListSource Members
     
            public bool ContainsListCollection
            {
                get { return false; }
            }
     
            public IList<TValue> GetList()
            {
                return Values;
            }
     
            #endregion
        }
    - Enfin j'ai crée une classe AdvancedCustomNotifySource<T> qui s'insère entre la CsutomSortedList et la datasource du control. Cette classe implémente IBindinList. Elle récupère les valeurs de la CsutomSortedList et les insère dans une bindingList . Tous changements de la datasource déclanche l'évenement ListChanged de AdvancedCustomNotifySource<T> et notifie ainsi les changements au contrôle auquel elle est bindé. Pour cela la datasource (c.a.d ma CustomSortedList) doit implémenter INotifyListSource<T>.

    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
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
     
        public class AdvancedCustomNotifySource<T> : CustomBindingSourceBase
        {
            protected INotifyListSource<T> dataSource = null;
     
            private IList<T> internalList;
     
            public IList<T> InternalList
            {
                get { return internalList; }
                set { internalList = value; }
            }
     
            protected override IBindingList List
            {
                get
                {
                    if (InternalList == null)
                        InternalList = ((IList<T>)ListBindingHelper<T>.GetList(dataSource));
                    return new System.ComponentModel.BindingList<T>((IList<T>)InternalList);
                }
            }
     
            public INotifyListSource<T> DataSource
            {
                get { return dataSource; }
                set
                {
                    dataSource = value;
                    dataSource.CollectionChanged += new NotifyCollectionChangedEventHandler(dataSource_CollectionChanged);
                }
            }
     
            void dataSource_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
            {
                ListChangedType t;
                if (e.NewItems.Count != 0)
                    t = ListChangedType.ItemAdded;
                else if (e.OldItems.Count != 0)
                    t = ListChangedType.ItemDeleted;
                else if (e.OldStartingIndex != e.NewStartingIndex)
                    t = ListChangedType.ItemMoved;
                else
                    t = ListChangedType.ItemChanged;
                OnListChanged(this, new ListChangedEventArgs(t, e.NewStartingIndex, e.OldStartingIndex));
            }
     
            #region ITypedList Members
     
            public override PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors)
            {
                PropertyDescriptorCollection sourceProps;
                if (dataSource == null)
                    sourceProps = PropertyDescriptorCollection.Empty;
     
                object obj1 = ListBindingHelper.GetList(this.dataSource);
                sourceProps = ListBindingHelper.GetListItemProperties(obj1, listAccessors);
     
                return sourceProps;
            }
     
            public override string GetListName(PropertyDescriptor[] listAccessors)
            {
                object obj1 = ListBindingHelper.GetList(this.dataSource);
                return ListBindingHelper.GetListName(obj1, listAccessors);
            }
     
            #endregion
        }
     
        public static class ListBindingHelper<T>
        {
            public static object GetList(object list)
            {
                if (list is IListSource<T>)
                    return ((IListSource<T>)list).GetList();
                return ListBindingHelper.GetList(list);
            }
        }
     
        public abstract class CustomBindingSourceBase : IBindingList, ITypedList
        {
            protected abstract IBindingList List { get; }
     
            protected void OnListChanged(object sender, ListChangedEventArgs e)
            {
                if (ListChanged != null)
                    ListChanged(sender, e);
            }
     
            #region IBindingList Members
     
            public void AddIndex(PropertyDescriptor property)
            {
                List.AddIndex(property);
            }
     
            public object AddNew()
            {
                return List.AddNew();
            }
     
            public bool AllowEdit
            {
                get { return List.AllowEdit; }
            }
     
            public bool AllowNew
            {
                get { return List.AllowNew; }
            }
     
            public bool AllowRemove
            {
                get { return List.AllowRemove; }
            }
     
            public void ApplySort(PropertyDescriptor property, ListSortDirection direction)
            {
                List.ApplySort(property, direction);
            }
     
            public int Find(PropertyDescriptor property, object key)
            {
                return List.Find(property, key);
            }
     
            public bool IsSorted
            {
                get { return List.IsSorted; }
            }
     
            public event ListChangedEventHandler ListChanged;
     
            public void RemoveIndex(PropertyDescriptor property)
            {
                List.RemoveIndex(property);
            }
     
            public void RemoveSort()
            {
                List.RemoveSort();
            }
     
            public ListSortDirection SortDirection
            {
                get { return List.SortDirection; }
            }
     
            public PropertyDescriptor SortProperty
            {
                get { return List.SortProperty; }
            }
     
            public bool SupportsChangeNotification
            {
                get { return List.SupportsChangeNotification; }
            }
     
            public bool SupportsSearching
            {
                get { return List.SupportsSearching; }
            }
     
            public bool SupportsSorting
            {
                get { return List.SupportsSorting; }
            }
     
            #endregion
     
            #region ICollection Members
     
            public void CopyTo(Array array, int index)
            {
                List.CopyTo(array, index);
            }
     
            public bool IsSynchronized
            {
                get { return List.IsSynchronized; }
            }
     
            public object SyncRoot
            {
                get { return List.SyncRoot; }
            }
     
            public int Count
            {
                get { return List.Count; }
            }
     
            #endregion
     
            #region IList Members
     
            public int Add(object value)
            {
                return List.Add(value);
            }
     
            public void Clear()
            {
                List.Clear();
            }
     
            public bool Contains(object value)
            {
                return List.Contains(value);
            }
     
            public int IndexOf(object value)
            {
                return List.IndexOf(value);
            }
     
            public void Insert(int index, object value)
            {
                List.Insert(index, value);
            }
     
            public bool IsFixedSize
            {
                get { return List.IsFixedSize; }
            }
     
            public bool IsReadOnly
            {
                get { return List.IsReadOnly; }
            }
     
            public void Remove(object value)
            {
                List.Remove(value);
            }
     
            public void RemoveAt(int index)
            {
                List.RemoveAt(index);
            }
     
            public object this[int index]
            {
                get
                {
                    return List[index];
                }
                set
                {
                    List[index] = value;
                }
            }
     
            #endregion
     
            #region IEnumerable Members
     
            public IEnumerator GetEnumerator()
            {
                return List.GetEnumerator();
            }
     
            #endregion
     
            #region ITypedList Members
     
            public abstract PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors);
     
            public abstract string GetListName(PropertyDescriptor[] listAccessors);
     
            #endregion
        }
    Bon le code est un peu long à lire à cause des longues implémentations d'interfaces, mais ça marche bien.

  5. #5
    Membre émérite
    Avatar de shwin
    Profil pro
    Inscrit en
    Novembre 2003
    Messages
    568
    Détails du profil
    Informations personnelles :
    Localisation : Canada

    Informations forums :
    Inscription : Novembre 2003
    Messages : 568
    Par défaut
    Pk ne pas avoir fait une class qui hérite de list et de INotifyPropertyChanged ?

    Chaque changement de ta list va déclanger ListChanged et tu as juste a mettre rafraichir ton binding dans ton handler

  6. #6
    maa
    maa est déconnecté
    Membre éclairé
    Avatar de maa
    Inscrit en
    Octobre 2005
    Messages
    672
    Détails du profil
    Informations personnelles :
    Âge : 41

    Informations forums :
    Inscription : Octobre 2005
    Messages : 672
    Par défaut
    Pk ne pas avoir fait une class qui hérite de list et de INotifyPropertyChanged ?
    Ma classe hérite déjà de SortedList.

    tu as juste a mettre rafraichir ton binding dans ton handler
    Je ne comprends pas. Pourrais-tu donner un petit exemple ?

    Implémenter INotifyPropertyChanged suffit à faire qu'une modification de ma collection sera automatiquement répercutée dans le contrôle auquel elle est bindé ? Je sais que ce n'est pas le cas avec INotifyCollectionChanged. Mais ça marche avec IBindingList.

  7. #7
    Rédacteur
    Avatar de Thomas Lebrun
    Profil pro
    Inscrit en
    Octobre 2002
    Messages
    9 161
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France

    Informations forums :
    Inscription : Octobre 2002
    Messages : 9 161
    Par défaut
    Citation Envoyé par maa Voir le message
    Implémenter INotifyPropertyChanged suffit à faire qu'une modification de ma collection sera automatiquement répercutée dans le contrôle auquel elle est bindé ?

    Oui, c'est le but: si ta classe implémente cette interface, dès qu'une propriété est modifiée, un evènement est généré. Le contrôle auquel ta classe est bindée est notifié de cet évènement et met à jour l'interface.

  8. #8
    maa
    maa est déconnecté
    Membre éclairé
    Avatar de maa
    Inscrit en
    Octobre 2005
    Messages
    672
    Détails du profil
    Informations personnelles :
    Âge : 41

    Informations forums :
    Inscription : Octobre 2005
    Messages : 672
    Par défaut
    Oui, c'est le but: si ta classe implémente cette interface, dès qu'une propriété est modifiée, un evènement est généré. Le contrôle auquel ta classe est bindée est notifié de cet évènement et met à jour l'interface.
    Non je parlais d'une collection. Je veux que quand celle-ci est bindé à un contrôle (une combobox par exemple), ce dernier soit automatiquement mis à jour dès qu'une modification à lieu dans ma collection. Je crois pour cela ma collection doit forcément implémenter IBindingList, non ?

  9. #9
    Rédacteur
    Avatar de Thomas Lebrun
    Profil pro
    Inscrit en
    Octobre 2002
    Messages
    9 161
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France

    Informations forums :
    Inscription : Octobre 2002
    Messages : 9 161
    Par défaut
    Je pense plutôt que c'est INotifyCollectionChanged que ta collection doit implémenter....

  10. #10
    maa
    maa est déconnecté
    Membre éclairé
    Avatar de maa
    Inscrit en
    Octobre 2005
    Messages
    672
    Détails du profil
    Informations personnelles :
    Âge : 41

    Informations forums :
    Inscription : Octobre 2005
    Messages : 672
    Par défaut
    Oui c'est ce que j'ai fait, mais ça ne suffit pas pour que le contrôle soit mis à jour à chaque changement de ma collection. C'est pourquoi j'ai crée une classe AdvancedCustomNotifySource<T> qui implémente IBindingList, capture les événements CollectionChanged de ma datasource (qui implémente INotifyCollectionChanged) et renvoi un événement ListChanged. En insérant cet intermédiaire entre ma SortedList et la datasource de mon contrôle, celui-ci est automatiquement notifié de tout changements de ma SortedList.

  11. #11
    Membre émérite
    Profil pro
    Inscrit en
    Septembre 2003
    Messages
    652
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2003
    Messages : 652
    Par défaut
    Dites, question bête. Ce databinding super génial qui permet de faire ce qu'on veut avec les sources de données en mettant tous les contrôles liés à jour de manière transparente... c'est suffisamment rentable pour justifier de se prendre autant la tête et de pondre autant de code, juste pour éviter de faire une méthode qui fait
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    comboBox.Items.Clear();
    foreach ( int key in dictionary.Keys )
      comboBox.Items.Add( dictionary[ key ] );
    et qu'on appelle quand on a fini de tripoter les données en question ?

    J'ai dû rater quelque chose. Les trucs qui font tout automatiquement c'est bien, mais s'il faut passer 2 jours et se trimballer des interfaces obscures et lourdingues pour les faire marcher correctement alors qu'en 5mn on fait ça beaucoup plus simplement à la main...

  12. #12
    maa
    maa est déconnecté
    Membre éclairé
    Avatar de maa
    Inscrit en
    Octobre 2005
    Messages
    672
    Détails du profil
    Informations personnelles :
    Âge : 41

    Informations forums :
    Inscription : Octobre 2005
    Messages : 672
    Par défaut
    J'ai dû rater quelque chose. Les trucs qui font tout automatiquement c'est bien, mais s'il faut passer 2 jours et se trimballer des interfaces obscures et lourdingues pour les faire marcher correctement alors qu'en 5mn on fait ça beaucoup plus simplement à la main...
    C'est vrai. C'était plus un défi personnel. Par contre ça peut être réutilisé.

  13. #13
    Rédacteur
    Avatar de SaumonAgile
    Homme Profil pro
    Team leader
    Inscrit en
    Avril 2007
    Messages
    4 028
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Moselle (Lorraine)

    Informations professionnelles :
    Activité : Team leader
    Secteur : Conseil

    Informations forums :
    Inscription : Avril 2007
    Messages : 4 028
    Par défaut
    Citation Envoyé par Maniak Voir le message
    J'ai dû rater quelque chose. Les trucs qui font tout automatiquement c'est bien, mais s'il faut passer 2 jours et se trimballer des interfaces obscures et lourdingues pour les faire marcher correctement alors qu'en 5mn on fait ça beaucoup plus simplement à la main...
    Plusieurs explications :
    1. Une fois qu'on sait le faire, il est très rapide de le faire pour d'autres projets.
    2. On n'est pas forcément dirigé par une logique de productivité.
    3. Tu peux te construire une maison avec morceaux de tole, cependant tu habites dans un batiment construit avec des materiaux solides et disposant de tout le confort nécessaire. Pourtant la cabane en tole aurait été beaucoup plus rapide à construire.


    EDIT : maa a répondu plus vite
    Besoin d'un MessageBox amélioré ? InformationBox pour .NET 1.1, 2.0, 3.0, 3.5, 4.0 sous license Apache 2.0.

    Bonnes pratiques pour les accès aux données
    Débogage efficace en .NET
    LINQ to Objects : l'envers du décor

    Mon profil LinkedIn - MCT - MCPD WinForms - MCTS Applications Distribuées - MCTS WCF - MCTS WCF 4.0 - MCTS SQL Server 2008, Database Development - Mon blog - Twitter

  14. #14
    maa
    maa est déconnecté
    Membre éclairé
    Avatar de maa
    Inscrit en
    Octobre 2005
    Messages
    672
    Détails du profil
    Informations personnelles :
    Âge : 41

    Informations forums :
    Inscription : Octobre 2005
    Messages : 672
    Par défaut
    Je pense quand même que le databinding pourrait être amélioré dans une future version du framework (plus facile à mettre en place pour des collections personnalisées). Pensez-vous que ça soit dans les projets de microsoft ?

  15. #15
    Rédacteur
    Avatar de Thomas Lebrun
    Profil pro
    Inscrit en
    Octobre 2002
    Messages
    9 161
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France

    Informations forums :
    Inscription : Octobre 2002
    Messages : 9 161
    Par défaut
    Citation Envoyé par maa Voir le message
    Oui c'est ce que j'ai fait, mais ça ne suffit pas pour que le contrôle soit mis à jour à chaque changement de ma collection. C'est pourquoi j'ai crée une classe AdvancedCustomNotifySource<T> qui implémente IBindingList, capture les événements CollectionChanged de ma datasource (qui implémente INotifyCollectionChanged) et renvoi un événement ListChanged. En insérant cet intermédiaire entre ma SortedList et la datasource de mon contrôle, celui-ci est automatiquement notifié de tout changements de ma SortedList.
    Il faudrait que je fasse des tests car je trouve cela très étrange: je sais avec certitude que cela fonctionne avec INotifyPropertyChanged: je ne vois pas pourquoi cela ne fonctionnerait pas dans le cas d'une collection implémentant INotifyCollectionChanged

  16. #16
    Membre émérite
    Profil pro
    Inscrit en
    Septembre 2003
    Messages
    652
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2003
    Messages : 652
    Par défaut
    Citation Envoyé par SaumonAgile Voir le message
    Plusieurs explications :
    1. Une fois qu'on sait le faire, il est très rapide de le faire pour d'autres projets.
    2. On n'est pas forcément dirigé par une logique de productivité.
    3. Tu peux te construire une maison avec morceaux de tole, cependant tu habites dans un batiment construit avec des materiaux solides et disposant de tout le confort nécessaire. Pourtant la cabane en tole aurait été beaucoup plus rapide à construire.
    Mmh, oui et non. Sur le principe on est d'accord, sauf que tu as l'air de considérer que les matériaux solides et tout le confort nécessaire, c'est un système qui oblige à implémenter des interfaces qui te font pondre 3 pages de code juste pour pouvoir mettre à jour une liste. Je ne vois pas trop où est le confort là-dedans, et encore moins où sont les matériaux solides (parce que mine de rien, ça fait du code plus compliqué que nécessaire, et du code plus compliqué que nécessaire est rarement synonyme de 'solide' :)

    Après si tu considères que le confort c'est de pouvoir rendre un collection modifiable par n'importe qui et ne rien avoir à faire pour gérer la mise à jour des contrôles liés, ok. Sauf que rendre une collection modifiable par n'importe qui n'est pas vraiment une recommandation niveau design :)

  17. #17
    Membre émérite
    Avatar de shwin
    Profil pro
    Inscrit en
    Novembre 2003
    Messages
    568
    Détails du profil
    Informations personnelles :
    Localisation : Canada

    Informations forums :
    Inscription : Novembre 2003
    Messages : 568
    Par défaut
    Voici un exemple avec INotifyPropertyChanged.
    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
     
    namespace WindowsApplication13
    {
    	public partial class Form1 : Form
    	{
    		public Form1()
    		{
    			InitializeComponent();
    			l.ItemChanged += new EventHandler<EventArgs>(l_ItemChanged);
    		}
     
    		void l_ItemChanged(object sender, EventArgs e)
    		{
    			comboBox1.DataSource = null;
    			comboBox1.DataSource = l;
    			comboBox1.DisplayMember = "Name";
    		}
     
     
     
    		UserList l = new UserList();
    		private void button1_Click(object sender, EventArgs e)
    		{
    			l.Add(new User("a"));
    			l.Add(new User("b"));
    			l.Add(new User("c"));
     
    			comboBox1.DataSource = l;
    			comboBox1.DisplayMember = "Name";
    		}
     
    		private void button2_Click(object sender, EventArgs e)
    		{
    			l[0].Name = "zzz";
    		}
     
     
    	}
     
    	public class User: INotifyPropertyChanged
    	{
    		public User()
    		{ } 
     
    		public User(string name)
    		{
    			Name = name;
    		}
     
    		private string _name;
     
    		public  string Name
    		{
    			get { return _name; }
    			set 
    			{
     
    				_name = value;
    				PropertyChangedEventArgs e = new PropertyChangedEventArgs("Name");
     
    				OnPropertyChanged(e);
     
    			}
    		}
     
    		#region INotifyPropertyChanged Members
     
    		public event PropertyChangedEventHandler PropertyChanged;
     
    		public void OnPropertyChanged(PropertyChangedEventArgs e)
    		{
    			if (PropertyChanged != null)
    				PropertyChanged(this, e);
    		}
     
    		#endregion
    	}
     
    	public class UserList : List<User>
    	{
     
    		public new void Add(User item)
    		{
    			base.Add(item);
    			item.PropertyChanged += new PropertyChangedEventHandler(item_PropertyChanged);
    		}
     
    		void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
    		{
    			OnItemChanged();
    		}
     
    		public event EventHandler<EventArgs> ItemChanged;
     
    		protected virtual void OnItemChanged()
    		{
    			if (ItemChanged != null)
    				ItemChanged(this, EventArgs.Empty);
    		}
    	}
     
     
     
     
    }

  18. #18
    maa
    maa est déconnecté
    Membre éclairé
    Avatar de maa
    Inscrit en
    Octobre 2005
    Messages
    672
    Détails du profil
    Informations personnelles :
    Âge : 41

    Informations forums :
    Inscription : Octobre 2005
    Messages : 672
    Par défaut
    Merci pour ton code shwin :

    Ce que je n'aime pas trop dedans, c'est ça :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
    		void l_ItemChanged(object sender, EventArgs e)
    		{
    			comboBox1.DataSource = null;
    			comboBox1.DataSource = l;
    			comboBox1.DisplayMember = "Name";
    		}
    Ici on redéfini manuellement la datasource à chaque changement d'un Item dans la collection... Pour que le binding soit automatiquement mis à jour, il me semble qu'il aurait nécessairement fallu que UserList implémente IBindingList, non ?
    En tout cas, implémenter INotifyCollectionChanged ne suffit pas. D'abord il n'y a pas d'élément dans l'énumération NotifyCollectionChangedAction qui décrit qu'un Item de la collection à été modifié. Mais même si l'on souhaite être notifié de l'ajout d'un item dans la collection, implémenter INotifyCollectionChanged ne suffit toujours pas pour que le binding soit automatiquement mis à jour. Voici un exemple qui illustre cela (j'ai modifié l'exemple précédent).

    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
     
        public partial class Form1 : Form
        {
            UserList l = new UserList();
     
            public Form1()
            {
                InitializeComponent();
            }
     
            private void button1_Click(object sender, EventArgs e)
            {
                l.Add(new User("a"));
                l.Add(new User("b"));
                l.Add(new User("c"));
     
                comboBox1.DataSource = l;
                comboBox1.DisplayMember = "Name";
            }
     
            private void button2_Click(object sender, EventArgs e)
            {
                l.Add(new User("d"));
            }
        }
     
        public class User : INotifyPropertyChanged
        {
            public User() { }
     
            public User(string name)
            {
                Name = name;
            }
     
            private string _name;
     
            public string Name
            {
                get { return _name; }
                set
                {
                    _name = value;
                    PropertyChangedEventArgs e = new PropertyChangedEventArgs("Name");
                    OnPropertyChanged(e);
                }
            }
     
            #region INotifyPropertyChanged Members
     
            public event PropertyChangedEventHandler PropertyChanged;
     
            public void OnPropertyChanged(PropertyChangedEventArgs e)
            {
                if (PropertyChanged != null)
                    PropertyChanged(this, e);
            }
     
            #endregion
        }
     
        public class UserList : List<User>, INotifyCollectionChanged
        {
            public new void Add(User item)
            {
                base.Add(item);
                if(CollectionChanged !=null)
                    CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, this.Count - 1));
            }
     
            #region INotifyCollectionChanged Members
     
            public event NotifyCollectionChangedEventHandler CollectionChanged;
     
            #endregion
        }
    Si UserList avait implémenté IBindingList, ça aurait bien marché. Le problème est qu'implémenter IBindingList est beaucoup plus lourd... dommage

  19. #19
    Membre émérite
    Avatar de shwin
    Profil pro
    Inscrit en
    Novembre 2003
    Messages
    568
    Détails du profil
    Informations personnelles :
    Localisation : Canada

    Informations forums :
    Inscription : Novembre 2003
    Messages : 568
    Par défaut
    Citation Envoyé par maa Voir le message
    Merci pour ton code shwin :

    Ce que je n'aime pas trop dedans, c'est ça :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
    		void l_ItemChanged(object sender, EventArgs e)
    		{
    			comboBox1.DataSource = null;
    			comboBox1.DataSource = l;
    			comboBox1.DisplayMember = "Name";
    		}

    Si UserList avait implémenté IBindingList, ça aurait bien marché. Le problème est qu'implémenter IBindingList est beaucoup plus lourd... dommage
    Je suis daccord avec ce code, il est moche. Mais c'est fait sur un coin de table!!

    Pk ne pas dit que UserList est un bindingList ?
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
     
    public class UserList : BindingList<User>
    	{
    		protected override void OnListChanged(ListChangedEventArgs e)
    		{
    			base.OnListChanged(e);
    		}
    ...
    C'est tres légé et tu fait ce que tu veux dans ton ListChanged et le params e.

    Je suis en 2.0 donc jai pas access à INotifyCollectionChanged.

  20. #20
    Membre émérite
    Avatar de shwin
    Profil pro
    Inscrit en
    Novembre 2003
    Messages
    568
    Détails du profil
    Informations personnelles :
    Localisation : Canada

    Informations forums :
    Inscription : Novembre 2003
    Messages : 568
    Par défaut
    Voici ce que je viens de pondre avec INotifyPropertyChanged. Ca fonctionne #1 pour le changed et add
    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
     
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Xml.Serialization;
    using System.Xml;
    using System.Text.RegularExpressions;
    using System.Diagnostics;
    using System.Data.Sql;
    using System.Data.SqlClient;
    namespace WindowsApplication13
    {
    	public partial class Form1 : Form
    	{
    		public Form1()
    		{
    			InitializeComponent();
    		}
     
    		UserList l = new UserList();
    		private void button1_Click(object sender, EventArgs e)
    		{
    			l.Add(new User("a"));
    			l.Add(new User("b"));
    			l.Add(new User("c"));
     
    			comboBox1.DataSource = l;
    			comboBox1.DisplayMember = "Name";
    		}
     
    		private void button2_Click(object sender, EventArgs e)
    		{
    			l[0].Name = "zzz";
    			l.Add(new User("test"));
    		}
    	}
     
    	public class User: INotifyPropertyChanged
    	{
    		public User()
    		{ } 
     
    		public User(string name)
    		{
    			Name = name;
    		}
     
    		private string _name;
     
    		public  string Name
    		{
    			get { return _name; }
    			set 
    			{
     
    				_name = value;
     
    				OnPropertyChanged(new PropertyChangedEventArgs("Name"));
    			}
    		}
     
    		#region INotifyPropertyChanged Members
     
    		public event PropertyChangedEventHandler PropertyChanged;
     
    		protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
    		{
    			if (PropertyChanged != null)
    				PropertyChanged(this, e);
    		}
    		#endregion
    	}
     
    	public class UserList : BindingList<User>, INotifyPropertyChanged
    	{
    		#region INotifyPropertyChanged Members
     
    		public event PropertyChangedEventHandler PropertyChanged;
     
    		protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
    		{
    			if (PropertyChanged != null)
    				PropertyChanged(this, e);
    		}
     
    		#endregion
    	}
     
     
     
     
    }

Discussions similaires

  1. [Flex4] Binding bidirectionel et mx:Tree
    Par vilveq dans le forum Flex
    Réponses: 1
    Dernier message: 04/08/2011, 09h47
  2. Récupérer l'adresse de bind d'un socket
    Par gloode dans le forum Réseau
    Réponses: 4
    Dernier message: 04/02/2005, 10h56
  3. Bind ou pas Bind?
    Par jonzuzu dans le forum MFC
    Réponses: 4
    Dernier message: 19/03/2004, 10h00
  4. []Erreur sur second emploi collection binding
    Par jacma dans le forum VB 6 et antérieur
    Réponses: 2
    Dernier message: 08/03/2004, 18h02
  5. Bind - sous-domaine
    Par _Gabriel_ dans le forum Réseau
    Réponses: 4
    Dernier message: 07/03/2004, 11h54

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