【问题标题】:Data binding combobox with list from WCF Service带有 WCF 服务列表的数据绑定组合框
【发布时间】:2013-12-27 01:14:11
【问题描述】:

我正在为使用 WCF 服务从数据库接收数据的 Windows 商店开发应用程序(MVVM 模式)。 我想将一个类别列表数据绑定到组合框中,但它不适合我,我搜索了网络并没有找到解决方案。

班级类别:

   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}"/>

视图模型:

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

在 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);

有人吗???

【问题讨论】:

  • 您是否调试过实际失败的原因?您实际上是否在 OnNavigatedTo 函数中获取值?输出部分是否有错误?您的 ViewModel 是否实现了 INotifyPropertyChanged?请提供更多信息。

标签: c# wpf wcf mvvm combobox


【解决方案1】:

您需要实现 INotifyPropertyChanged 以让 UI 知道您已更改 ListCategories 集合。

在您的 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");
            }
        }
    }

【讨论】:

    猜你喜欢
    • 2014-08-25
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    • 2011-01-15
    • 2011-04-30
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    相关资源
    最近更新 更多