博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Mvvm模式学习
阅读量:5068 次
发布时间:2019-06-12

本文共 11426 字,大约阅读时间需要 38 分钟。

mvvm模式.先让xaml页面与xaml.cs分离。

原来是双击button生成个事件,添加代码,按钮的功能完成。要使页面与代码分离,最起码得把button事件的处理代码从xaml.cs文件中弄出去吧。

原来是直接双击,后台生成。现在不能双击了。麻烦但是有用。不经革命之痛苦,怎得革命之幸福。

找个代码,改改理解理解吧。发现要实现点击得数据绑定。

        <Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top"  Command="{Binding Path=ShowCommand}" Width="75" Margin="331,224,0,0"/>

既然是绑定就得有数据上下文。查找发现有

<Grid.DataContext>

           <local:ShowViewModel />
       </Grid.DataContext>

那么就得有xmlns:local="clr-namespace:mccmlearn.ViewModel"

页面代码:

后台代码不用贴了因为什么也没有。

这是项目结构,看viewmodel中的ShowViewModel.cs

 

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Input;using mccmlearn.Commands;namespace mccmlearn.ViewModel{    internal class ShowViewModel    {        private DelegateCommand showCommand;        public ICommand ShowCommand        {            get            {                if (showCommand == null)                    showCommand = new DelegateCommand(new Action(ShowExecuted), new Func
(ShowCanExecute)); return showCommand; } } private bool ShowCanExecute() { return true; } private void ShowExecuted() { System.Windows.MessageBox.Show("dd"); } }}

下面是DelegateCommand类,从网上找的,

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows.Input;namespace mccmlearn.Commands{    ///     ///     This class allows delegating the commanding logic to methods passed as parameters,    ///     and enables a View to bind commands to objects that are not part of the element tree.    ///     public class DelegateCommand : ICommand    {        #region Constructors        ///         ///     Constructor        ///         public DelegateCommand(Action executeMethod)            : this(executeMethod, null, false)        {        }        ///         ///     Constructor        ///         public DelegateCommand(Action executeMethod, Func
canExecuteMethod) : this(executeMethod, canExecuteMethod, false) { } ///
/// Constructor /// public DelegateCommand(Action executeMethod, Func
canExecuteMethod, bool isAutomaticRequeryDisabled) { if (executeMethod == null) { throw new ArgumentNullException("executeMethod"); } _executeMethod = executeMethod; _canExecuteMethod = canExecuteMethod; _isAutomaticRequeryDisabled = isAutomaticRequeryDisabled; } #endregion #region Public Methods ///
/// Method to determine if the command can be executed /// public bool CanExecute() { if (_canExecuteMethod != null) { return _canExecuteMethod(); } return true; } ///
/// Execution of the command /// public void Execute() { if (_executeMethod != null) { _executeMethod(); } } ///
/// Property to enable or disable CommandManager's automatic requery on this command /// public bool IsAutomaticRequeryDisabled { get { return _isAutomaticRequeryDisabled; } set { if (_isAutomaticRequeryDisabled != value) { if (value) { CommandManagerHelper.RemoveHandlersFromRequerySuggested(_canExecuteChangedHandlers); } else { CommandManagerHelper.AddHandlersToRequerySuggested(_canExecuteChangedHandlers); } _isAutomaticRequeryDisabled = value; } } } ///
/// Raises the CanExecuteChaged event /// public void RaiseCanExecuteChanged() { OnCanExecuteChanged(); } ///
/// Protected virtual method to raise CanExecuteChanged event /// protected virtual void OnCanExecuteChanged() { CommandManagerHelper.CallWeakReferenceHandlers(_canExecuteChangedHandlers); } #endregion #region ICommand Members ///
/// ICommand.CanExecuteChanged implementation /// public event EventHandler CanExecuteChanged { add { if (!_isAutomaticRequeryDisabled) { CommandManager.RequerySuggested += value; } CommandManagerHelper.AddWeakReferenceHandler(ref _canExecuteChangedHandlers, value, 2); } remove { if (!_isAutomaticRequeryDisabled) { CommandManager.RequerySuggested -= value; } CommandManagerHelper.RemoveWeakReferenceHandler(_canExecuteChangedHandlers, value); } } bool ICommand.CanExecute(object parameter) { return CanExecute(); } void ICommand.Execute(object parameter) { Execute(); } #endregion #region Data private readonly Action _executeMethod = null; private readonly Func
_canExecuteMethod = null; private bool _isAutomaticRequeryDisabled = false; private List
_canExecuteChangedHandlers; #endregion } ///
/// This class allows delegating the commanding logic to methods passed as parameters, /// and enables a View to bind commands to objects that are not part of the element tree. /// ///
Type of the parameter passed to the delegates
public class DelegateCommand
: ICommand { #region Constructors ///
/// Constructor /// public DelegateCommand(Action
executeMethod) : this(executeMethod, null, false) { } ///
/// Constructor /// public DelegateCommand(Action
executeMethod, Func
canExecuteMethod) : this(executeMethod, canExecuteMethod, false) { } ///
/// Constructor /// public DelegateCommand(Action
executeMethod, Func
canExecuteMethod, bool isAutomaticRequeryDisabled) { if (executeMethod == null) { throw new ArgumentNullException("executeMethod"); } _executeMethod = executeMethod; _canExecuteMethod = canExecuteMethod; _isAutomaticRequeryDisabled = isAutomaticRequeryDisabled; } #endregion #region Public Methods ///
/// Method to determine if the command can be executed /// public bool CanExecute(T parameter) { if (_canExecuteMethod != null) { return _canExecuteMethod(parameter); } return true; } ///
/// Execution of the command /// public void Execute(T parameter) { if (_executeMethod != null) { _executeMethod(parameter); } } ///
/// Raises the CanExecuteChaged event /// public void RaiseCanExecuteChanged() { OnCanExecuteChanged(); } ///
/// Protected virtual method to raise CanExecuteChanged event /// protected virtual void OnCanExecuteChanged() { CommandManagerHelper.CallWeakReferenceHandlers(_canExecuteChangedHandlers); } ///
/// Property to enable or disable CommandManager's automatic requery on this command /// public bool IsAutomaticRequeryDisabled { get { return _isAutomaticRequeryDisabled; } set { if (_isAutomaticRequeryDisabled != value) { if (value) { CommandManagerHelper.RemoveHandlersFromRequerySuggested(_canExecuteChangedHandlers); } else { CommandManagerHelper.AddHandlersToRequerySuggested(_canExecuteChangedHandlers); } _isAutomaticRequeryDisabled = value; } } } #endregion #region ICommand Members ///
/// ICommand.CanExecuteChanged implementation /// public event EventHandler CanExecuteChanged { add { if (!_isAutomaticRequeryDisabled) { CommandManager.RequerySuggested += value; } CommandManagerHelper.AddWeakReferenceHandler(ref _canExecuteChangedHandlers, value, 2); } remove { if (!_isAutomaticRequeryDisabled) { CommandManager.RequerySuggested -= value; } CommandManagerHelper.RemoveWeakReferenceHandler(_canExecuteChangedHandlers, value); } } bool ICommand.CanExecute(object parameter) { // if T is of value type and the parameter is not // set yet, then return false if CanExecute delegate // exists, else return true if (parameter == null && typeof(T).IsValueType) { return (_canExecuteMethod == null); } return CanExecute((T)parameter); } void ICommand.Execute(object parameter) { Execute((T)parameter); } #endregion #region Data private readonly Action
_executeMethod = null; private readonly Func
_canExecuteMethod = null; private bool _isAutomaticRequeryDisabled = false; private List
_canExecuteChangedHandlers; #endregion } ///
/// This class contains methods for the CommandManager that help avoid memory leaks by /// using weak references. /// internal class CommandManagerHelper { internal static void CallWeakReferenceHandlers(List
handlers) { if (handlers != null) { // Take a snapshot of the handlers before we call out to them since the handlers // could cause the array to me modified while we are reading it. EventHandler[] callees = new EventHandler[handlers.Count]; int count = 0; for (int i = handlers.Count - 1; i >= 0; i--) { WeakReference reference = handlers[i]; EventHandler handler = reference.Target as EventHandler; if (handler == null) { // Clean up old handlers that have been collected handlers.RemoveAt(i); } else { callees[count] = handler; count++; } } // Call the handlers that we snapshotted for (int i = 0; i < count; i++) { EventHandler handler = callees[i]; handler(null, EventArgs.Empty); } } } internal static void AddHandlersToRequerySuggested(List
handlers) { if (handlers != null) { foreach (WeakReference handlerRef in handlers) { EventHandler handler = handlerRef.Target as EventHandler; if (handler != null) { CommandManager.RequerySuggested += handler; } } } } internal static void RemoveHandlersFromRequerySuggested(List
handlers) { if (handlers != null) { foreach (WeakReference handlerRef in handlers) { EventHandler handler = handlerRef.Target as EventHandler; if (handler != null) { CommandManager.RequerySuggested -= handler; } } } } internal static void AddWeakReferenceHandler(ref List
handlers, EventHandler handler) { AddWeakReferenceHandler(ref handlers, handler, -1); } internal static void AddWeakReferenceHandler(ref List
handlers, EventHandler handler, int defaultListSize) { if (handlers == null) { handlers = (defaultListSize > 0 ? new List
(defaultListSize) : new List
()); } handlers.Add(new WeakReference(handler)); } internal static void RemoveWeakReferenceHandler(List
handlers, EventHandler handler) { if (handlers != null) { for (int i = handlers.Count - 1; i >= 0; i--) { WeakReference reference = handlers[i]; EventHandler existingHandler = reference.Target as EventHandler; if ((existingHandler == null) || (existingHandler == handler)) { // Clean up old handlers that have been collected // in addition to the handler that is to be removed. handlers.RemoveAt(i); } } } } }}

这样就实现了按钮的事件,没有写在.xaml.cs里面。

转载于:https://www.cnblogs.com/shiyue/archive/2013/01/24/2874736.html

你可能感兴趣的文章
【BJOI2018】求和
查看>>
百度前端开发规范 by fex-team
查看>>
PPT母版制作
查看>>
求用1g、2g、3g的砝码(每种砝码有无穷多个)称出10g的方案有几种
查看>>
使用hexdump追踪FAT32文件系统中的一个文件
查看>>
C#验证邮箱,电话,手机,数字,英文,日期,身份证,邮编,网址,IP类.. (转)
查看>>
Python callable() 函数
查看>>
蓝牙4.0入门
查看>>
React setState 没有反应
查看>>
[召集] .NET Framework基本类库中的设计模式
查看>>
DP方程整理
查看>>
goto命令
查看>>
第2周学习进度
查看>>
修改系统的shell
查看>>
Opencv DNN 物体检测
查看>>
C++定义动态数组
查看>>
步步为营-84-数字转化为金额的Js+enter键取消页面刷新
查看>>
插入排序
查看>>
反刍我的傻瓜时代(四)
查看>>
try...catch...
查看>>