恭喜,你发布的帖子
发布于 2020-02-01 21:54:35
3楼
2.3 一个ViewModel的实现。这里只有一个MainWindow窗口,所以只有一个MainWindowViewModel。
这里同时用两个按钮测试了Prism库中的DelegateCommand,一个附带传string类型参数,另一个传Object类型参数。生产中用Prism的库会更方便,而且有框架直接提供。不过还是需要自己知道底层实现的原理,。
using Microsoft.Win32;
using Prism.Commands;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace WpfApp01.ViewModels
{
public class MainWindowViewModel : NotificationObject
{
private bool enableFlag = true;
public bool EnableFlag
{
get { return enableFlag; }
set
{
enableFlag = value;
this.RaisePropertyChanged("EnableFlag");
}
}
private double input1;
public double Input1
{
get { return input1; }
set
{
input1 = value;
this.RaisePropertyChanged("Input1");
}
}
private double input2;
public double Input2
{
get { return input2; }
set
{
input2 = value;
this.RaisePropertyChanged("Input2");
}
}
private double result;
public double Result
{
get { return result; }
set
{
result = value;
this.RaisePropertyChanged("Result");
}
}
public ClassICommand CommandAdd { get; set; }
public ClassICommand CommandPopDiag { get; set; }
public ClassICommand CommandEnable { get; set; }
public ICommand CommandMsg
{
get
{
return new DelegateCommand<string>((str) =>
{
MessageBox.Show("Button's parameter:" + str);
});
}
}
public ICommand ButtonCommand2
{
get
{
return new DelegateCommand<Button>((button) =>
{
MessageBox.Show(button.Content.ToString());
if (button.Content.ToString() == "Clicked-1")
{
button.Content = "Clicked-2";
}
else
{
button.Content = "Clicked-1";
}
});
}
}
//Action方法
private void Add(object parameter)
{
this.Result = this.Input1 + this.Input2;
MessageBox.Show("Working");
}
private void PopDiag(object parameter)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.ShowDialog();
}
private void Enabler(object parameter)
{
if (!this.EnableFlag)
this.EnableFlag = true;
else
this.EnableFlag = false;
}
public MainWindowViewModel()
{
this.CommandAdd = new ClassICommand();
CommandAdd.ExcuteAction = new Action<object>(this.Add);
this.CommandPopDiag = new ClassICommand();
CommandPopDiag.ExcuteAction = new Action<object>(this.PopDiag);
this.CommandEnable = new ClassICommand();
CommandEnable.ExcuteAction = new Action<object>(this.Enabler);
}
}
}
请填写推广理由:
分享
只看
楼主