我的 View 模型中有一个移动服务集合,它从云中的移动服务数据库获取数据。我正在尝试将此 MobileServiceCollection 绑定(bind)到我的 ui 中的列表框(带有项目模板)。但是由于 Query 命令是异步的,所以 ui 不会更新。这是我在异步接收数据之前设置 Listbox.ItemSource。 (我知道数据是通过断点接收的。(我知道我的绑定(bind)是正确的,我在单击按钮后设置了 Listbox.Itemsource 然后数据显示在我的 ui 中)。
我知道这可能与 NotifyChange 有关,所以我尝试实现它。但我无法让它工作。所以基本上我的问题是:
如何使用表示为 MobileSericeCollection 的异步数据源更新我的 ui 中的列表框。
这是我到目前为止所拥有的:
xml:
<ListBox x:Name="ListOfProducts" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock x:Name="tb1" Margin="0,0,0,0" Text="{Binding ProductName, Mode=TwoWay}"></TextBlock>
<TextBlock x:Name="tb2" Margin="200,0,0,0" Text="{Binding ProductPrice, Mode=TwoWay}"></TextBlock>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
后面的代码:
public partial class ProductList : PhoneApplicationPage
{
ProductListViewModel plvm = new ProductListViewModel();
public ProductList()
{
InitializeComponent();
ListOfProducts.ItemsSource = plvm.P;
}
}
View 模型:
class ProductListViewModel
{
public MobileServiceCollection<Product, Product> P;
public ProductListViewModel()
{
getProducts();
}
/// <summary>
/// Fetch all products from the database (async).
/// </summary>
private async void getProducts()
{
P = await App.MobileService.GetTable<Product>()
//.Where(Product => Product.ProductName == "tomato")
.OrderByDescending(Product => Product.ProductPrice)
.ToCollectionAsync();
}
}
模型:
[DataContract]
public class Product
{
[DataMember(Name = "id")]
public string id { get; set; }
[DataMember(Name = "ProductName")]
public string ProductName { get; set; }
[DataMember(Name = "ProductPrice")]
public float ProductPrice { get; set; }
}
如果有人可以帮助我解决这个问题,那就太感谢了
最佳答案
尝试这样做:
第一 ,让你的ProductListViewModel
实现 INotifyPropertyChanged
.
第二 , 制作 P
属性而不是字段/成员,因为数据绑定(bind)仅适用于公共(public)属性。并正确提出属性更改通知:
private MobileServiceCollection<Product, Product> _p;
public MobileServiceCollection<Product, Product> P
{
get { return _p; }
set
{
_p = value;
NotifyPropertyChanged("P");
}
}
第三 ,正确设置 View 的DataContext。相对于 View 的当前 DataContext 的数据绑定(bind)解析路径:
ProductListViewModel plvm = new ProductListViewModel();
public ProductList()
{
InitializeComponent();
this.DataContext = plvm;
}
第四 , 设置
ItemsSource
到 P
的绑定(bind)路径DataContext/ProductListViewModel 的属性:<ListBox x:Name="ListOfProducts" ItemsSource="{Binding P}">
关于c# - 绑定(bind) MobileServiceCollection 未在 UI (MVVM) 中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22472994/