Link to home
Create AccountLog in
Avatar of Xrth
Xrth

asked on

Binding List<string> to Combobox

I want to bind a List to a combobox. But somehow its not working.
If i assigne the data to the combobox its showing up, but if i change the datasource later, its not updating. So basically the binding is ot working.
I dont know if it is importent or not but the class is a singleton.
// Here is the Class
 
public class Items : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    static Items instance = null;
    static readonly object padlock = new object();
 
    Items()
    {
    }
 
    public static Items Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Items();
                }
                return instance;
            }
        }
    }
 
    public void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this,
                new PropertyChangedEventArgs(propertyName));
        }
 
    }
 
    public List<string> _ItemList = new List<string>();
    public List<string> ItemList 
    {            
        get
        {
            return _ItemList;                
        }
 
        set
        {
            _ItemList = value;
            NotifyPropertyChanged("items");
        }
    }
}
 
//Here is the xaml code of the combobox
<ComboBox ItemsSource="{Binding  ItemList, Mode=OneWay}" 
 
// This is a function of the c# file from the UC where i want to bind the data
 
        private void btnLoad_Click(object sender, RoutedEventArgs e)
        {
            if (items.ItemList.Count <= 0)
            {
                con.sendData("LoadItems");
            }
            ddItems.DataContext = Classes.Singleton.Items.Instance;
        }

Open in new window

Avatar of AndreSteffens
AndreSteffens

I think you need the line
NotifyPropertyChanged("items");
 
to read:
NotifyPropertyChanged("ItemList");
       
ASKER CERTIFIED SOLUTION
Avatar of Xrth
Xrth

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Realize this is closed and points awarded, but you may want to use ObservableCollection<string> instead of List<string>.  In your case, the ComboBox was only getting updated when the whole collection was changed (when ItemList referenced an entirely different instance of List<string>).  Binding to an ObservableCollection<string> will give provide notification when elements in the collection or added, changed, or removed, and subsequently update the UI.