接前文,咱们继续开源WPF控件探索HandyControl,本文主要写给如我这种新人菜鸟、
首先我们新建一个WPF项目,HandyControlEasyDemo
使用Nuget来安装我们需要引用的两个重要工具HandyControl 以及MVVMlight组件(MVVMlight是WPF项目下一个很好用的框架,MVVM相关资料写得非常好的 推荐大家看翁智华的 利刃 MVVMLight 1:MVVMLight介绍以及在项目中的使用 - 翁智华 - 博客园 点此处直达)
安装后,我们先来配置下MVVMlight ,首先新建两个文件夹 Model View 以后我们的模型均放置在Model命名空间下,视图均放置在View命名空间下,入下图,三个文件夹中的大写字母依次是MVVM 这难道就是MVVM的由来 哈哈
在Model 文件夹新建TestModel类,类声明如下 public class TestModel: ObservableObject
将MainViewModel拖放到View文件下
主页面这么写
<Window
x:Class="HandyControlEasyDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:controls="clr-namespace:HandyControl.Controls;assembly=HandyControl"
DataContext="{Binding Main,Source={StaticResource Locator}}"
mc:Ignorable="d"
Title="MainWindow"
Height="450"
Width="800">
<Grid>
<StackPanel
HorizontalAlignment="Left">
<controls:ProgressButton
Height="30"
Width="100"
Margin="5"
Background="#20B2AA"
Style="{StaticResource ProgressButtonPrimary}"
IsChecked="{Binding IsUploading,Mode=TwoWay}"
Progress="{Binding ProcessValue}"
Content="{Binding IsUploading,Converter={StaticResource Boolean2StrConverter},ConverterParameter='上传数据;上传数据中'}"
Command="{Binding Source={StaticResource Locator},Path = Main.UpLoadDataCmd}" />
</StackPanel>
</Grid>
</Window>
using System.Threading;
using GalaSoft.MvvmLight;
using HandyControlEasyDemo.Common;
namespace HandyControlEasyDemo.Model
{
public class TestModel: ObservableObject
{
public BackgroundTaskWork BackTaskWork
{
get => _pBackTaskWork;
set
{
_pBackTaskWork = value;
RaisePropertyChanged(() => BackTaskWork);
}
}
private BackgroundTaskWork _pBackTaskWork = new BackgroundTaskWork();
internal void StartTask()
{
BackTaskWork.DoBackTask(UploadScanData);
}
private bool UploadScanData()
{
bool result = true;
// 2.初始化数据、进度条及相关功能
BackTaskWork.UpdateProcess(this, 100, 1, "提交扫码数据");
for (int x = 0; x < 100; x++)
{
// 模拟任务处理
Thread.Sleep(20);
BackTaskWork.UpdateProcess(this, 100, x, x + "/" + 100);
}
return result;
}
}
}
上面代码中用到的异步线程处理类我放在项目中了,感兴趣的亲们可以直接下载项目实际看下,这个简单的DEMO亮点在进度条按钮的属性处理,相关代码取自HandyControl的DEMO,加上了一些自己的辅助类,感兴趣的亲可以参考下