Il est juste nécessaire de travailler sur un ObservableCollection et charger uniquement AddRange (pas utiliser « Ajouter »)
Lorsque nous chargeons les données suivantes:
foreach (object item in items)
{
MyList.Add(item); // Where MyList is a ObservableCollection
}
Puis après avoir ajouté du premier élément l'appel ObservableCollection OnCollectionChanged. Ensuite, le ComboBox va essayer de sélectionner la SelectedValue et retourner 'null' quand ne peut pas trouver cet élément.
Il peut résoudre un problème:
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
namespace System.Collections.ObjectModel
{
/// <summary>
/// Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.
/// </summary>
/// <typeparam name="T"></typeparam>
public class ObservableCollectionEx<T> : ObservableCollection<T>
{
/// <summary>
/// Initializes a new instance of the System.Collections.ObjectModel.ObservableCollection(Of T) class.
/// </summary>
public ObservableCollectionEx()
: base() { }
/// <summary>
/// Initializes a new instance of the System.Collections.ObjectModel.ObservableCollection(Of T) class that contains elements copied from the specified collection.
/// </summary>
/// <param name="collection">collection: The collection from which the elements are copied.</param>
/// <exception cref="System.ArgumentNullException">The collection parameter cannot be null.</exception>
public ObservableCollectionEx(IEnumerable<T> collection)
: base(collection) { }
/// <summary>
/// Adds the elements of the specified collection to the end of the ObservableCollection(Of T).
/// </summary>
public void AddRange(IEnumerable<T> collection)
{
//
// Add the items directly to the inner collection
//
foreach (var data in collection)
{
this.Items.Add(data);
}
//
// Now raise the changed events
//
this.OnPropertyChanged(new PropertyChangedEventArgs("Count"));
this.OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
}
Pouvez-vous poster le XAML pertinent et/ou C#? Cela pourrait nous aider à comprendre ce que vous essayez de faire et à réduire le problème. – Andy