简体   繁体   中英

Databinding Listbox Winforms

This will have been answered in the other numerous threads on databinding and implementing INotifyPropertyChanged. However, I am still have difficulty getting this to work.

Essentially I have two listboxes, when the user selects the server name from the first listbox the second is supposed to provide a list of databases on that server. Pretty simple. The second listbox however is not displaying the updated list of databases.

Here is the code: Code to exec query and add data to the DatabaseList property.

        private void selection_Server_SelectionChangeCommitted(object sender, EventArgs e)
    {
        server = (string)selection_Server.SelectedItem;
        try
        {
            ExecDBList(server, ref vm);
        }

Class that manages properties used on the window.

    public class VM : INotifyPropertyChanged
{
    private static List<string> _dblist;
    public  List<string> DatabaseList
    {
        get
        {
            return _dblist;
        }
        set
        {
            if (_dblist != value)
            {
                _dblist = value;
            };
        }
    }
    public VM() { }

    void OnPropertyChanged(string PropertyName)
    {
            PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
    }

    public event PropertyChangedEventHandler PropertyChanged;

Code line on MainWindow initialization that assigns the listbox DataSource

            selection_RDM.DataSource = vm.DatabaseList;

Any help in getting this to work would be much appreciated as I'm struggling to understand the previous answers to databinding and using PropertyChangedEventHandler.

Thank you Richard

Try adding OnPropertyChanged(); after setting the value on _dblist like this:

public  List<string> DatabaseList
{
    get
    {
        return _dblist;
    }
    set
    {
        if (_dblist != value)
        {
            _dblist = value;
            OnPropertyChanged("DatabaseList");
        };
    }
}

There is no place where you call the notify so your application will not be notified about something that changed

Or better

change your OnPropertyChanged(string name) to private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")

and call this method without the name of the property on the same place as where i showed your like this

if (_dblist != value)
{
    _dblist = value;
    NotifyPropertyChanged();
};

Not working WinForms recently, but working with WPF, Have you tried doing

RaisePropertyChanged( "DatabaseList" );

This way, after you've requeried the private list entries, anything bound to it should be notified... hey your source was just updated... get a fresh list of that too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM