介绍
重新想象 Windows 8 Store Apps 之 绑定
通过 MVVM 模式实现数据的添 加、删除、修改和查询
示例
1、Model 层
Binding/MVVM/Model/ProductDatabase.cs
/* * Model 层的数据持久化操作(本地或远程) * * 本例只是一个演示 */ using System; using System.Collections.Generic; using System.Linq; namespace XamlDemo.Binding.MVVM.Model { public class ProductDatabase { private List<Product> _products = null; public List<Product> GetProducts() { if (_products == null) { Random random = new Random(); _products = new List<Product>(); for (int i = 0; i < 100; i++) { _products.Add( new Product { ProductId = i, Name = "Name" + i.ToString().PadLeft(4, '0'), Category = "Category" + (char)random.Next(65, 91) }); } } return _products; } public List<Product> GetProducts(string name, string category) { return GetProducts().Where(p => p.Name.Contains(name) && p.Category.Contains(category)).ToList(); } public void Update(Product product) { var oldProduct = _products.Single(p => p.ProductId == product.ProductId); oldProduct = product; } public Product Add(string name, string category) { Product product =new Product(); product.ProductId = _products.Max(p => p.ProductId) + 1; product.Name = name; product.Category = category; _products.Insert(0, product); return product; } public void Delete(Product product) { _products.Remove(product); } } }
Binding/MVVM/Model/Product.cs
/* * Model 层的实体类,如果需要通知则需要实现 INotifyPropertyChanged 接口 */ using System.ComponentModel; namespace XamlDemo.Binding.MVVM.Model { public class Product : INotifyPropertyChanged { public Product() { ProductId = 0; Name = ""; Category = ""; } private int _productId; public int ProductId { get { return _productId; } set { _productId = value; RaisePropertyChanged("ProductId"); } } private string _name; public string Name { get { return _name; } set { _name = value; RaisePropertyChanged("Name"); } } private string _category; public string Category { get { return _category; } set { _category = value; RaisePropertyChanged("Category"); } } public event PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string name) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(name)); } } } }
以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索mvvm开发
, string
, mvvm
, public
, name
, mvvm模式
, category
, #MVVM
, 1-Model层
mvvm库
,以便于您获取更多的相关知识。
时间: 2024-09-12 08:05:37