简体   繁体   English

带有WCF服务列表的数据绑定组合框

[英]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. 我正在开发使用WCF服务从Windows接收数据的Windows存储应用程序(MVVM模式)。 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: 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: 在OnNavigatedTo函数中:

   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. 您需要实现INotifyPropertyChanged ,以便让UI知道您已经更改了ListCategories集合。

In your ViewModel, implement interface INotifyPropertyChanged 在您的ViewModel中,实现接口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");
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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