WPF之MVVM(Step3)——使用Prism(1)

时间:2023-03-09 19:41:49
WPF之MVVM(Step3)——使用Prism(1)

使用WPF-MVVM开发时,自己实现通知接口、DelegateCommand相对来说还是用的较少,我们更多的是使用第三方的MVVM框架,其中微软自身团队提供的就有Prism框架,此框架功能较多,本人现学有限,暂时先介绍简单的使用。

注:此处使用Prism版本4.1

Prism首先方便我们的是帮助我们实现了INotifyPropertyChanged接口,其中RaisePropertyChanged不仅实现利用字符串通知,更实现了Lambda表达式,这样在代码重构上提供了一些方便。。。

其次,Prism帮助我们实现了ICommand接口,可以利用其DelegateCommand实现。

下面为简要代码:

 class TestViewModel : NotificationObject
{
private string teststr;
/// <summary>
/// 待通知字符串
/// </summary>
public string TestStr
{
get { return teststr; }
set
{
teststr = value;
RaisePropertyChanged(()=>TestStr);
}
} /// <summary>
/// 测试命令
/// </summary>
public ICommand TestCommand { get; set; } public TestViewModel()
{
TestCommand = new DelegateCommand(Test,CanTest);
} int i = 0;
/// <summary>
/// testcommand执行的方法
/// </summary>
private void Test()
{
i++;
TestStr = i.ToString();
}
/// <summary>
/// testcommand是否可用
/// </summary>
/// <returns></returns>
private bool CanTest()
{
return true;
}
}

 

此处使用了Prism中的DelegateCommand,此类用于无需传递参数使用,下篇将描述使用DelegateCommand<T>创建可以传递参数的Command。

 


项目代码托管地址:https://wpfmvvm.codeplex.com/