MVVM: 通过 Binding 或 x:Bind 结合 Command 实现,通过 ButtonBase 触发命令
介绍
背水一战 Windows 10 之 MVVM(Model-View-ViewModel)
- 通过 Binding 或 x:Bind 结合 Command 实现,通过 ButtonBase 触发命令
示例
1、Model
MVVM/Model/Product.cs

/*
* Model 层的实体类,如果需要通知则需要实现 INotifyPropertyChanged 接口
*/ using System.ComponentModel; namespace Windows10.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(nameof(ProductId));
}
} private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
RaisePropertyChanged(nameof(Name));
}
} private string _category;
public string Category
{
get { return _category; }
set
{
_category = value;
RaisePropertyChanged(nameof(Category));
}
} public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
}

MVVM/Model/ProductDatabase.cs

/*
* Model 层的数据持久化操作(本地或远程)
*
* 本例只是一个演示
*/ using System;
using System.Collections.Generic;
using System.Linq; namespace Windows10.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);
}
}
}

2、ViewModel
MVVM/ViewModel1/MyCommand.cs

/*
* 为了方便使用,把 ICommand 再封装一层
*/ using System;
using System.Windows.Input; namespace Windows10.MVVM.ViewModel1
{
public class MyCommand : ICommand
{
// 由 public void Execute(object parameter) 调用的委托
public Action<object> MyExecute { get; set; } // 由 public bool CanExecute(object parameter) 调用的委托
public Func<object, bool> MyCanExecute { get; set; } public MyCommand(Action<object> execute, Func<object, bool> canExecute)
{
this.MyExecute = execute;
this.MyCanExecute = canExecute;
} // 需要发布此事件的话,则调用 RaiseCanExecuteChanged 方法即可
public event EventHandler CanExecuteChanged;
public void RaiseCanExecuteChanged()
{
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
} // 用于决定当前绑定的 Command 能否被执行
// parameter 是由 ButtonBase 的 CommandParameter 传递过来的
// 如果返回 false 则对应的 ButtonBase 将变为不可用
public bool CanExecute(object parameter)
{
return this.MyCanExecute == null ? true : this.MyCanExecute(parameter);
} // 用于执行对应的命令,只有在 CanExecute() 返回 true 时才可以被执行
// parameter 是由 ButtonBase 的 CommandParameter 传递过来的对象
public void Execute(object parameter)
{
this.MyExecute(parameter);
}
}
}

MVVM/ViewModel1/ProductViewModel.cs

/*
* ViewModel 层
*
* 注:为了方便使用,此例对 ICommand 做了一层封装。如果需要了解比较原始的 MVVM 实现请参见 http://www.cnblogs.com/webabcd/archive/2013/08/29/3288304.html
*/ using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using Windows10.MVVM.Model; namespace Windows10.MVVM.ViewModel1
{
public class ProductViewModel : INotifyPropertyChanged
{
// 用于提供 Products 数据
private ObservableCollection<Product> _products;
public ObservableCollection<Product> Products
{
get { return _products; }
set
{
_products = value;
RaisePropertyChanged(nameof(Products));
}
} // 用于“添加”和“查询”的 Product 对象
private Product _product;
public Product Product
{
get { return _product; }
set
{
_product = value;
RaisePropertyChanged(nameof(Product));
}
} // 数据库对象
private ProductDatabase _context = null; public ProductViewModel()
{
_context = new ProductDatabase(); Product = new Product();
Products = new ObservableCollection<Product>(_context.GetProducts());
} private MyCommand _getProductsCommand;
public MyCommand GetProductsCommand
{
get
{
return _getProductsCommand ?? (_getProductsCommand = new MyCommand
((object obj) =>
{
// 从 Model 层获取数据
Products = new ObservableCollection<Product>(_context.GetProducts(Product.Name, Product.Category));
},
null));
}
} private MyCommand _addProductCommand;
public MyCommand AddProductCommand
{
get
{
return _addProductCommand ?? (_addProductCommand = new MyCommand
((object obj) =>
{
// 在 Model 层添加一条数据
Product newProduct = _context.Add(Product.Name, Product.Category); // 更新 ViewModel 层数据
Products.Insert(0, newProduct);
},
null));
}
} private MyCommand _updateProductCommand;
public MyCommand UpdateProductCommand
{
get
{
return _updateProductCommand ?? (_updateProductCommand = new MyCommand
((object obj) =>
{
// 通过 CommandParameter 传递过来的数据
Product product = obj as Product; // 更新 ViewModel 层数据
product.Name = product.Name + "U";
product.Category = product.Category + "U"; // 更新 Model 层数据
_context.Update(product);
},
// 对应 ICommand 的 CanExecute(),如果返回 false 则对应的 ButtonBase 将变为不可用
(object obj) => obj != null));
}
} private MyCommand _deleteProductCommand;
public MyCommand DeleteProductCommand
{
get
{
return _deleteProductCommand ?? (_deleteProductCommand = new MyCommand
((object obj) =>
{
// 通过 CommandParameter 传递过来的数据
Product product = obj as Product; // 更新 Model 层数据
_context.Delete(product); // 更新 ViewModel 层数据
Products.Remove(product);
},
// 对应 ICommand 的 CanExecute(),如果返回 false 则对应的 ButtonBase 将变为不可用
(object obj) => obj != null));
}
} public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
}

3、View
MVVM/View/Demo1.xaml

<Page
x:Class="Windows10.MVVM.View.Demo1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Windows10.MVVM.View"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" xmlns:vm="using:Windows10.MVVM.ViewModel1"> <Grid Background="Transparent">
<StackPanel Margin="10 0 10 10"> <!--
View 层
--> <!--
本例通过 Binding 结合 Command 实现 MVVM(用 x:Bind 结合 Command 实现 MVVM 也是一样的),通过 ButtonBase 触发命令
--> <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 Text="{Binding Name}" HorizontalAlignment="Left" />
<TextBlock 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 Text="Name:" VerticalAlignment="Center" />
<TextBox Name="txtName" Text="{Binding Name, Mode=TwoWay}" Width="100" />
<TextBlock Text="Category:" VerticalAlignment="Center" Margin="20 0 0 0" />
<TextBox Name="txtCategory" Text="{Binding Category, Mode=TwoWay}" Width="100" />
</StackPanel> <!--
ButtonBase
Command - 指定关联的 ICommand
CommandParameter - 传递给 ICommand 的参数
-->
<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: 通过 Binding 或 x:Bind 结合 Command 实现,通过 ButtonBase 触发命令的更多相关文章
- 背水一战 Windows 10 (24) - MVVM: 通过 Binding 或 x:Bind 结合 Command 实现,通过非 ButtonBase 触发命令
[源码下载] 背水一战 Windows 10 (24) - MVVM: 通过 Binding 或 x:Bind 结合 Command 实现,通过非 ButtonBase 触发命令 作者:webabcd ...
- 背水一战 Windows 10 (23) - MVVM: 通过 Binding 或 x:Bind 结合 Command 实现,通过 ButtonBase 触发命令
[源码下载] 背水一战 Windows 10 (23) - MVVM: 通过 Binding 或 x:Bind 结合 Command 实现,通过 ButtonBase 触发命令 作者:webabcd ...
- MVVM: 通过 Binding 或 x:Bind 结合 Command 实现,通过非 ButtonBase 触发命令
介绍背水一战 Windows 10 之 MVVM(Model-View-ViewModel) 通过 Binding 或 x:Bind 结合 Command 实现,通过非 ButtonBase 触发命令 ...
- How to bind a Command on a ContextMenu within a DataTemplate using MVVM
Since the Popuup control has it's separate visual tree, you cannot use find ancestor to find the Gri ...
- MVVM模式解析和在WPF中的实现(三)命令绑定
MVVM模式解析和在WPF中的实现(三) 命令绑定 系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二)数据绑定 MVVM模式解析和在WPF中 ...
- command not found,系统很多命令都用不了 ,修改环境变量
bash: ***: command not found,系统很多命令都用不了,均提示没有此命令. 突然之间linux很多命令都用不了,均提示没有此命令. 这应该是系统环境变量出现了问题导致的. 解决 ...
- (WPF, MVVM) Slider Binding.
对于Button的Command的绑定可以通过实现ICommand接口来进行,但是Slider并没有Command属性. 另外如果要实现MVVM模式的话,需要将一些Method和Slider的Even ...
- MVVM模式应用 之为ApplicationBarIconButton 添加Command操作属性
在学习MVVM的过程中,总是会遇到挫折,一碰到就是花费好长时间去解决..唉,不求量,只求质. 第一种(已经实践成功): (1)http://bindableapplicationb.codeplex. ...
- (WPF, MVVM) Textbox Binding
参考:http://msdn.microsoft.com/en-us/library/system.windows.data.updatesourcetrigger(v=vs.110).aspx Te ...
随机推荐
- GIT安装和使用
GIT 首先登陆github账号 在本地创建一个文件夹 点击文件夹,右键,选择Git create repository here 操作之后,会生成一个.git文件(这个文件为隐藏文件) 在此 ...
- Zygote进程【1】——Zygote的诞生
在Android中存在着C和Java两个完全不同的世界,前者直接建立在Linux的基础上,后者直接建立在JVM的基础上.zygote的中文名字为"受精卵",这个名字很好的诠释了zy ...
- sudo命令使用的几个场景
在linux系统下,普通用户无法直接执行root用户权限下的命令,如果想让普通用户执行只有root用户才能执行的操作命令.下面罗列下经常使用sudo命令的几个场景: 1.用户无权限执行root命令普通 ...
- 学习下nginx负载均衡--深入理解nginx
作为代理服务器,一般都需要向上游服务器转发请求.这里的负载均衡是指通过一种策略尽量把请求平均的分发都上游服务器 1.upstream 语法 upstream name {} 配置快: http 栗子( ...
- js 增删改查方法
push() 向数组的末尾添加一个或多个元素 pop() 删除数组内部并返回数组的最后一个元素 shift() 把数组内部的第一个元素从其中删除,并返回第一个元素的值 unshift() 向数组外部的 ...
- Java集合系列:-----------06List的总结(LinkedList,ArrayList等使用场景和性能分析)
现在,我们再回头看看总结一下List.内容包括:第1部分 List概括第2部分 List使用场景第3部分 LinkedList和ArrayList性能差异分析第4部分 Vector和ArrayList ...
- 如何让oracle的select强制走索引
大多数情况下,oracle数据库内置的查询优化策略还是很成功的,但偶尔也有犯2的时候,即使有索引,也会做全表扫描,可以参考以下语句的写法,强制让select语句使用索引 CREATE OR REPLA ...
- 前端见微知著JavaScript基础篇:this or that ?
上节,我们提到了this关键字的问题,并且追加了一句很有意义的话:谁调用我,我指向谁.的确,在javascript中,在默认情况下,this会指向一个已经初始化的window对象.所以你不论有多少全局 ...
- 【福吧资源网整理】老男孩-python运维6期 不加密
老男孩-python运维6期 不加密,连夜整理出来分享给大家老男孩的python教程确实不错. 教程目录: 下载地址:http://www.fu83.cn/thread-204-1-1.html
- linux中vi编辑器的使用
vi编辑器是所有Unix及Linux系统下标准的编辑器,它的强大不逊色于任何最新的文本 编辑器,这里只是简单地介绍一下它的用法和一小部分指令.由于对Unix及Linux系统的任 何版本,vi编辑器是完 ...