简体   繁体   中英

Binding combobox - WPF & C#

I have read loads of posts about this topic, but I cannot for the life of me figure this out, so your help is appreciated as I am losing the will to live!

I am trying to bind a list to a combobox in WPF, here is my code:

ViewModel:

 public class ViewModelAddRegion
  {    
    public List<DataAccessLayer.Model.CountryList> CountryList { get; set; }

    public object GetCountryList()
    {
        List<DataAccessLayer.Model.CountryList> CountryList = new List<DataAccessLayer.Model.CountryList>();
        CountryList = Data.DatabaseGets.GetAllCountries();
        return CountryList;
    }
}

So that gets my list. In the backing to my window, the code is:

public AddRegion()
    {
        var vm = new WineDatabase.ViewModel.ViewModelAddRegion();      
        var CountryAllList = vm.GetCountryList();
        DataContext = CountryAllList;
        InitializeComponent();
    }

And finally, in my window:

<ComboBox Name="CountryList"
                  Margin="159,0,-160,0" 
                  Grid.Row="1" 
                  Grid.RowSpan="2" 
                  ItemsSource="{Binding CountryAllList}"
                  DisplayMemberPath="CountryName"/>

Debugging, my list is populated as expected, but the combobox is forever empty.

Thanks for any assistance at all!

CountryAllList is just a local variable that you can't bind to. See the Data Binding Overview article on MSDN for details.

You should assign the ViewModel instance to the DataContext

var vm = new WineDatabase.ViewModel.ViewModelAddRegion();
vm.CountryList = vm.GetCountryList();
DataContext = vm;

and bind to its CountryList property

<ComboBox ItemsSource="{Binding CountryList}" ... />

Finally, in your GetCountryList method, it doesn't make much sense to assign the return value of Data.DatabaseGets.GetAllCountries() to a local variable. You could instead directly return it from the method.

public List<DataAccessLayer.Model.CountryList> GetCountryList()
{
    return Data.DatabaseGets.GetAllCountries();
}

The GetCountryList() method may as well directly assign to the CountryList property

public void GetCountryList()
{
    CountryList = Data.DatabaseGets.GetAllCountries();
}

and you could write the initialization code like this:

var vm = new WineDatabase.ViewModel.ViewModelAddRegion();
vm.GetCountryList();
DataContext = vm;

Change AddRegion method to:

public AddRegion()
{
    var vm = new WineDatabase.ViewModel.ViewModelAddRegion();      
    vm.CountryList = vm.GetCountryList();
    DataContext = vm;
    InitializeComponent();
}

And in ComboBox set ItemsSource="{Binding CountryList}"

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