[源码下载]

背水一战 Windows 10 (23) - MVVM: 通过 Binding 或 x:Bind 结合 Command 实现,通过 ButtonBase 触发命令

作者:webabcd

介绍
背水一战 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 = ;
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 = ; 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);
}
}
}

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(, 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>

OK
[源码下载]

背水一战 Windows 10 (23) - MVVM: 通过 Binding 或 x:Bind 结合 Command 实现,通过 ButtonBase 触发命令的更多相关文章

  1. 背水一战 Windows 10 (24) - MVVM: 通过 Binding 或 x:Bind 结合 Command 实现,通过非 ButtonBase 触发命令

    [源码下载] 背水一战 Windows 10 (24) - MVVM: 通过 Binding 或 x:Bind 结合 Command 实现,通过非 ButtonBase 触发命令 作者:webabcd ...

  2. 背水一战 Windows 10 (25) - MVVM: 通过 x:Bind 实现 MVVM(不用 Command)

    [源码下载] 背水一战 Windows 10 (25) - MVVM: 通过 x:Bind 实现 MVVM(不用 Command) 作者:webabcd 介绍背水一战 Windows 10 之 MVV ...

  3. 背水一战 Windows 10 (22) - 绑定: 通过 Binding 绑定对象, 通过 x:Bind 绑定对象, 通过 Binding 绑定集合, 通过 x:Bind 绑定集合

    [源码下载] 背水一战 Windows 10 (22) - 绑定: 通过 Binding 绑定对象, 通过 x:Bind 绑定对象, 通过 Binding 绑定集合, 通过 x:Bind 绑定集合 作 ...

  4. 背水一战 Windows 10 (119) - 后台任务: 后台下载任务(任务分组,组完成后触发后台任务)

    [源码下载] 背水一战 Windows 10 (119) - 后台任务: 后台下载任务(任务分组,组完成后触发后台任务) 作者:webabcd 介绍背水一战 Windows 10 之 后台任务 后台下 ...

  5. MVVM: 通过 Binding 或 x:Bind 结合 Command 实现,通过 ButtonBase 触发命令

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

  6. MVVM: 通过 Binding 或 x:Bind 结合 Command 实现,通过非 ButtonBase 触发命令

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

  7. 背水一战 Windows 10 (120) - 后台任务: 后台上传任务

    [源码下载] 背水一战 Windows 10 (120) - 后台任务: 后台上传任务 作者:webabcd 介绍背水一战 Windows 10 之 后台任务 后台上传任务 示例演示 uwp 的后台上 ...

  8. 背水一战 Windows 10 (118) - 后台任务: 后台下载任务(任务分组,并行或串行执行,组完成后通知)

    [源码下载] 背水一战 Windows 10 (118) - 后台任务: 后台下载任务(任务分组,并行或串行执行,组完成后通知) 作者:webabcd 介绍背水一战 Windows 10 之 后台任务 ...

  9. 背水一战 Windows 10 (117) - 后台任务: 后台下载任务

    [源码下载] 背水一战 Windows 10 (117) - 后台任务: 后台下载任务 作者:webabcd 介绍背水一战 Windows 10 之 后台任务 后台下载任务 示例演示 uwp 的后台下 ...

随机推荐

  1. 关闭form上chrome的autofill

    Chrome的autofill会自动找到form中的type=password的元素,然后把这个元素前面的元素当做是用户名,它不在乎这个元素叫什么名字.这样又是注册又是登录,你会发现它自作聪明的aut ...

  2. jQuery第一篇 (帅哥)

      同学心目中的jQuery: 简单易用,功能强大,对移动端来说,体积稍大. 1.1 回顾前面学到的js我们遇到的一些痛点 window.onload 事件有个事件覆盖的问题,我们只能写一个 代码容错 ...

  3. 没有Hyper-V服务,WP Emulator无法启动

    解决: 打开管理工具

  4. C#设计模式系列:职责链模式(Chain of Responsibility)

    1.职责链模式简介 1.1>.定义 职责链模式是一种行为模式,为解除请求的发送者和接收者之间的耦合,而使多个对象都有机会处理这个请求.将这些对象连接成一条链,并沿着这条链传递该请求,直到有一个对 ...

  5. 网络连接详细信息出现两个自动配置ipv4地址

    问题:网络连接详细信息出现两个自动配置ipv4地址,一个是有效地址,一个是无效地址. 解决办法:先将本地连接ip设置成自动获取,然后点击开始——>运行——>输入cmd,回车,进入命令行界面 ...

  6. String,StringBuffer与StringBuilder的区别??

    转自http://blog.csdn.net/rmn190/article/details/1492013 String 字符串常量 StringBuffer 字符串变量(线程安全) StringBu ...

  7. iframe跨域+

    script.image.iframe的src都不受同源策略的影响.所以我们可以借助这一特点,实现跨域.如前面所介绍的JSONP跨域,以及灯标(Beacons). 该篇随笔主要阐述iframe结合一些 ...

  8. Git版本控制Windows版快速上手

    说到版本控制,之前用过VSS,SVN,Git接触不久,感觉用着还行.写篇博文给大家分享一下使用Git的小经验,让大家对Git快速上手. 说白了Git就是一个控制版本的工具,其实没想象中的那么复杂,咱在 ...

  9. EntityFramework 7 OrderBy Skip Take-计算排序分页 SQL 翻译

    先解释一下这个标题的意思,OrderBy 在 Linq 语句中,我们经常使用,比如 OrderBy(b => b.BlogId) 就是对 BlogId 字段进行升序排序,这是针对一个字段的排序, ...

  10. Oracle数据库资源管理

    1.了解Resource Manager术语 2.了解Resource Manager分配方法 3.了解DEFAULT_PLAN 4.新建资源计划 5.创建使用者组 6.了解资源分配方法 7.分配使用 ...