简体   繁体   中英

Data binding combobox with list from WCF Service

I am developing an app(MVVM pattern) for windows store using WCF service to receive data from database. I want to data bind a list of categories into combobox, but it's not working for me, I searched the web and still didn't find a solution.

Class Category:

   public Category(Category c)
    {
        this.Id=c.Id;
        this.Name = c.Name;

    }
    public int Id { get; set; }
    public string Name { get; set; }

Xaml:

 <ComboBox x:Name="ChooseCategory"
   ItemsSource="{Binding ListCategories}"
                  DisplayMemberPath="Name"
                  SelectedValuePath="Id"
                  SelectedValue="{Binding SelectedItem, Mode=TwoWay}"/>

ViewModel:

public ObservableCollection<Category> ListCategories { get; private set; }

in the OnNavigatedTo function:

   var listCategory = await proxy.GetAllCategoriesAsync();
            List<Category> list = new List<Category>();
            foreach (var item in listCategory)
            {

                list.Add(new Category(item));
            }
            ListCategories = new ObservableCollection<Category>(list);

Anyone???

You need to implement INotifyPropertyChanged in order to let UI know that you have changed the ListCategories collection.

In your ViewModel, implement interface INotifyPropertyChanged

public class YourViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }

    private ObservableCollection<Category> _categories;
    public ObservableCollection<Category> ListCategories
    {
        get { return _categories; }
        set
        {
            if (_categories != value)
            {
                _categories = value;
                OnPropertyChanged("ListCategories");
            }
        }
    }

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