我正在使用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);
任何???
答案 0 :(得分:2)
您需要实施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");
}
}
}