重新想象 Windows 8 Store Apps (55) - 绑定: MVVM 模式
作者:webabcd
介绍
重新想象 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 = ; i < ; i++)
{
_products.Add(
new Product
{
ProductId = i,
Name = "Name" + i.ToString().PadLeft(, ''),
Category = "Category" + (char)random.Next(, )
});
}
} 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) + ;
product.Name = name;
product.Category = category; _products.Insert(, 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 = ;
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));
}
}
}
}
2、ViewModel 层
Binding/MVVM/ViewModel/ProductViewModel.cs
/*
* ViewModel 层
*/ using System.Collections.ObjectModel;
using System.Windows.Input;
using XamlDemo.Binding.MVVM.Model;
using System.Linq;
using System.ComponentModel; namespace XamlDemo.Binding.MVVM.ViewModel
{
public class ProductViewModel
{
// 用于提供 Products 数据
public ObservableCollection<Product> Products { get; set; }
// 用于“添加”和“查询”的 Product 对象
public Product Product { get; set; } private ProductDatabase _context = null; public ProductViewModel()
{
_context = new ProductDatabase(); Product = new Product();
Products = new ObservableCollection<Product>();
} // for 查询
public ICommand GetProductsCommand
{
get { return new GetProductsCommand(this); }
}
public void GetProducts(Product query)
{
// 从 Model 获取数据
var products = _context.GetProducts(query.Name, query.Category); // 更新 ViewModel 中的数据
Products.Clear();
foreach (var product in products)
{
Products.Add(product);
}
} // for 添加
public ICommand AddProductCommand
{
get { return new AddProductCommand(this); }
}
public void AddProduct(Product product)
{
// 更新 Model
var newProduct = _context.Add(product.Name, product.Category); // 更新 ViewModel
Products.Insert(, newProduct);
} // for 更新
public ICommand UpdateProductCommand
{
get { return new UpdateProductCommand(this); }
}
public void UpdateProduct(Product product)
{
// 更新 ViewModel
product.Name = product.Name + "U";
product.Category = product.Category + "U"; // 更新 Model
_context.Update(product);
} // for 删除
public ICommand DeleteProductCommand
{
get { return new DeleteProductCommand(this); }
}
public void DeleteProduct(Product product)
{
// 更新 Model
_context.Delete(product); // 更新 ViewModel
Products.Remove(product);
}
}
}
Binding/MVVM/ViewModel/AddProductCommand.cs
/*
* 添加 Product 数据的 Command
*/ using System;
using System.Windows.Input; namespace XamlDemo.Binding.MVVM.ViewModel
{
public class AddProductCommand : ICommand
{
private ProductViewModel _productViewModel; public AddProductCommand(ProductViewModel productViewModel)
{
_productViewModel = productViewModel;
} // parameter 是由 ButtonBase 的 CommandParameter 传递过来的
public bool CanExecute(object parameter)
{
return true;
} // 需要发布此事件的话,在 CanExecute() 方法中调用 OnCanExecuteChanged() 方法即可
public event EventHandler CanExecuteChanged;
protected virtual void OnCanExecuteChanged(EventArgs e)
{
if (CanExecuteChanged != null)
CanExecuteChanged(this, e);
} // parameter 是由 ButtonBase 的 CommandParameter 传递过来的
public void Execute(object parameter)
{
_productViewModel.AddProduct(_productViewModel.Product);
}
}
}
Binding/MVVM/ViewModel/DeleteProductCommand.cs
/*
* 删除 Product 数据的 Command
*/ using System;
using System.Windows.Input;
using XamlDemo.Binding.MVVM.Model; namespace XamlDemo.Binding.MVVM.ViewModel
{
public class DeleteProductCommand : ICommand
{
private ProductViewModel _productViewModel; public DeleteProductCommand(ProductViewModel productViewModel)
{
_productViewModel = productViewModel;
} // parameter 是由 ButtonBase 的 CommandParameter 传递过来的
// 当 ButtonBase 的 CommandParameter 中的数据发生变化时,会执行此方法
// 如果返回 false 则对应的 ButtonBase 将变为不可用
public bool CanExecute(object parameter)
{
var product = (Product)parameter;
if (product == null)
return false; return true;
} // 需要发布此事件的话,在 CanExecute() 方法中调用 OnCanExecuteChanged() 方法即可
public event EventHandler CanExecuteChanged;
protected virtual void OnCanExecuteChanged(EventArgs e)
{
if (CanExecuteChanged != null)
CanExecuteChanged(this, e);
} // parameter 是由 ButtonBase 的 CommandParameter 传递过来的
public void Execute(object parameter)
{
var product = (Product)parameter;
_productViewModel.DeleteProduct(product);
}
}
}
Binding/MVVM/ViewModel/UpdateProductCommand.cs
/*
* 更新 Product 数据的 Command
*/ using System;
using System.Windows.Input;
using XamlDemo.Binding.MVVM.Model; namespace XamlDemo.Binding.MVVM.ViewModel
{
public class UpdateProductCommand : ICommand
{
private ProductViewModel _productViewModel; public UpdateProductCommand(ProductViewModel productViewModel)
{
_productViewModel = productViewModel;
} // parameter 是由 ButtonBase 的 CommandParameter 传递过来的
// 当 ButtonBase 的 CommandParameter 中的数据发生变化时,会执行此方法
// 如果返回 false 则对应的 ButtonBase 将变为不可用
public bool CanExecute(object parameter)
{
var product = (Product)parameter;
if (product == null)
return false; return true;
} // 需要发布此事件的话,在 CanExecute() 方法中调用 OnCanExecuteChanged() 方法即可
public event EventHandler CanExecuteChanged;
protected virtual void OnCanExecuteChanged(EventArgs e)
{
if (CanExecuteChanged != null)
CanExecuteChanged(this, e);
} // parameter 是由 ButtonBase 的 CommandParameter 传递过来的
public void Execute(object parameter)
{
var product = (Product)parameter;
_productViewModel.UpdateProduct(product);
}
}
}
Binding/MVVM/ViewModel/GetProductsCommand.cs
/*
* 获取 Product 数据的 Command
*/ using System;
using System.Windows.Input; namespace XamlDemo.Binding.MVVM.ViewModel
{
public class GetProductsCommand : ICommand
{
private ProductViewModel _productViewModel; public GetProductsCommand(ProductViewModel productViewModel)
{
_productViewModel = productViewModel;
} // parameter 是由 ButtonBase 的 CommandParameter 传递过来的
public bool CanExecute(object parameter)
{
return true;
} // 需要发布此事件的话,在 CanExecute() 方法中调用 OnCanExecuteChanged() 方法即可
public event EventHandler CanExecuteChanged;
protected virtual void OnCanExecuteChanged(EventArgs e)
{
if (CanExecuteChanged != null)
CanExecuteChanged(this, e);
} // parameter 是由 ButtonBase 的 CommandParameter 传递过来的
public void Execute(object parameter)
{
_productViewModel.GetProducts(_productViewModel.Product);
}
}
}
3、View 层
Binding/MVVM/Demo.xaml
<Page
x:Class="XamlDemo.Binding.MVVM.Demo"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XamlDemo.Binding.MVVM"
xmlns:vm="using:XamlDemo.Binding.MVVM.ViewModel"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"> <Grid Background="Transparent">
<StackPanel Margin="120 0 0 0"> <!--
View 层
--> <StackPanel.DataContext>
<vm:ProductViewModel />
</StackPanel.DataContext> <ListView Name="listView" ItemsSource="{Binding Products}" Width="300" Height="300" HorizontalAlignment="Left" VerticalAlignment="Top">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="14.667" Text="{Binding Name}" HorizontalAlignment="Left" />
<TextBlock FontSize="14.667" Text="{Binding Category}" HorizontalAlignment="Left" Margin="10 0 0 0" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView> <StackPanel Orientation="Horizontal" Margin="0 10 0 0" DataContext="{Binding Product}">
<TextBlock FontSize="14.667" Text="Name:" VerticalAlignment="Center" />
<TextBox Name="txtName" Text="{Binding Name, Mode=TwoWay}" Width="200" />
<TextBlock FontSize="14.667" Text="Category:" VerticalAlignment="Center" Margin="20 0 0 0" />
<TextBox Name="txtCategory" Text="{Binding Category, Mode=TwoWay}" Width="200" />
</StackPanel> <!--
ButtonBase
Command - 指定关联的命令
CommandParameter - 传递给 Command 的参数
-->
<StackPanel Orientation="Horizontal" Margin="0 10 0 0">
<Button Name="btnSearch" Content="查询" Command="{Binding GetProductsCommand}" Margin="10 0 0 0" />
<Button Name="btnAdd" Content="添加" Command="{Binding AddProductCommand}" Margin="10 0 0 0" />
<Button Name="btnUpdate" Content="更新" Command="{Binding UpdateProductCommand}" CommandParameter="{Binding SelectedItem, ElementName=listView}" Margin="10 0 0 0" />
<Button Name="btnDelete" Content="删除" Command="{Binding DeleteProductCommand}" CommandParameter="{Binding SelectedItem, ElementName=listView}" Margin="10 0 0 0" />
</StackPanel> </StackPanel>
</Grid>
</Page> <!--
另外,MVVM Light Toolkit 是目前比较流行的 MVVM 框架,如果需要全 App 纯 MVVM 的话可以考虑
在 http://mvvmlight.codeplex.com/ 下载安装后,手动在安装目录的 Vsix 目录下安装相应的 VS 扩展(其中包括 MVVM Light Toolkit 的项目模板)
-->
OK
[源码下载]
重新想象 Windows 8 Store Apps (55) - 绑定: MVVM 模式的更多相关文章
- 重新想象 Windows 8 Store Apps (52) - 绑定: 与 Element Model Indexer Style RelativeSource 绑定, 以及绑定中的数据转换
[源码下载] 重新想象 Windows 8 Store Apps (52) - 绑定: 与 Element Model Indexer Style RelativeSource 绑定, 以及绑定中的数 ...
- 重新想象 Windows 8 Store Apps (53) - 绑定: 与 ObservableCollection CollectionViewSource VirtualizedFilesVector VirtualizedItemsVector 绑定
[源码下载] 重新想象 Windows 8 Store Apps (53) - 绑定: 与 ObservableCollection CollectionViewSource VirtualizedF ...
- 重新想象 Windows 8 Store Apps (54) - 绑定: 增量方式加载数据
[源码下载] 重新想象 Windows 8 Store Apps (54) - 绑定: 增量方式加载数据 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之 绑定 通过实 ...
- 重新想象 Windows 8 Store Apps 系列文章索引
[源码下载][重新想象 Windows 8.1 Store Apps 系列文章] 重新想象 Windows 8 Store Apps 系列文章索引 作者:webabcd 1.重新想象 Windows ...
- 重新想象 Windows 8 Store Apps (59) - 锁屏
[源码下载] 重新想象 Windows 8 Store Apps (59) - 锁屏 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之 锁屏 登录锁屏,获取当前程序的锁 ...
- 重新想象 Windows 8 Store Apps (15) - 控件 UI: 字体继承, Style, ControlTemplate, SystemResource, VisualState, VisualStateManager
原文:重新想象 Windows 8 Store Apps (15) - 控件 UI: 字体继承, Style, ControlTemplate, SystemResource, VisualState ...
- 重新想象 Windows 8 Store Apps (16) - 控件基础: 依赖属性, 附加属性, 控件的继承关系, 路由事件和命中测试
原文:重新想象 Windows 8 Store Apps (16) - 控件基础: 依赖属性, 附加属性, 控件的继承关系, 路由事件和命中测试 [源码下载] 重新想象 Windows 8 Store ...
- 重新想象 Windows 8 Store Apps (13) - 控件之 SemanticZoom
原文:重新想象 Windows 8 Store Apps (13) - 控件之 SemanticZoom [源码下载] 重新想象 Windows 8 Store Apps (13) - 控件之 Sem ...
- 重新想象 Windows 8 Store Apps (12) - 控件之 GridView 特性: 拖动项, 项尺寸可变, 分组显示
原文:重新想象 Windows 8 Store Apps (12) - 控件之 GridView 特性: 拖动项, 项尺寸可变, 分组显示 [源码下载] 重新想象 Windows 8 Store Ap ...
随机推荐
- Android杂谈--HTC等手机接收不到UDP广播报文的解决方案
最近遇到个问题,在android手机上发送UDP报文的时候,HTC等机型(测试用HTC new one)接收不到广播报文,而其他的samsung, huawei, xiaomi, nexus等等均没有 ...
- eclipse 代码提示时闪退问题
解决办法:在eclipse.ini里面最下面加上这句话 -Dorg.eclipse.swt.browser.DefaultType=mozilla
- 如何通过XShell传输文件
转载孟光孟叔的博客: https://learndevops.cn/index.php/2016/06/14/how-to-transfer-file-using-xshell xshell目前最好 ...
- 萝卜叶万能助手SEO网络营销简介
萝卜叶万能助手专业版是就是将我们10年的SEO经验和方法汇聚于一体的结晶,旨在打造一款使用简单方便,功能强大的SEO软件,以便节省您的时间,提高您收集资料.维护网站.发布帖子.进行网络营销的效率. 借 ...
- 公钥、私钥、CA认证、数字签名、U盾
感谢传智播客的方立勋老师,在一个教学视频上,他巧妙地以蒋介石给宋美龄写密信作为例子,生动地讲述了软件密码学知识. 加密分为对称加密和非对称加密,我们传统理解的,发送数据之前使用一个加密器加密,接到数据 ...
- 看上去很美 国内CDN现状与美国对比
CDN的理想与现实 多年以前,当<Kingdom of Heaven>这部史诗电影发行的时候,中国的影迷使用电驴和BT来寻找种子,而那个时候,高清也才刚刚进入电影领域,我的同事不惜用自家的 ...
- python watchdog
监视文件变更 #!/usr/bin/python # -*- coding:UTF-8 -*- import time from watchdog.observers import Observer ...
- 【cs229-Lecture19】微分动态规划
内容: 调试强化学习算法(RL算法) LQR线性二次型调节(french动态规划算法) 滤波(kalman filters) 线性二次高斯控制(LGG) Kalman滤波器 卡尔曼滤波(Kalman ...
- linux 环境变量设置及查看
1. 显示环境变量HOME $ echo $HOME /home/redbooks 2. 设置一个新的环境变量hello $ export HELLO="Hello!" $ ech ...
- PLSQL快捷补充代码设置
菜单Tools-->Preferences...然后依次选择下图红色选项 弹出下图对话框 输入需要快速生成的语句点击保存 点击Save后在slq窗口中输入 设置的语句缩写 列入:第一个sf 然 ...