当前位置:网站首页>How to use devaxpress WPF to create the first MVVM application in winui?
How to use devaxpress WPF to create the first MVVM application in winui?
2022-06-21 19:34:00 【Interface development Starling】
In this article, we will demonstrate how to create... From scratch WinUI MVVM Applications , And show in the process DevExpressWinUI MVVM The powerful functions of the framework .
DevExpress WPF v21.2 Official download
Initially we were WPF The platform created MVVM frame , Later, I found that the technology developed in this framework can be easily used in WinForms Use in , So we ported the framework there . stay v22.1 in , The official technical team aims at WinUI To optimize the MVVM frame , Keep the core functionality intact . If you use our WPF or WinForms Control , Is migrating to WinUI I don't have any problems with it .
Start by creating the bare view model , You can select the following view model types :
- View model generated at compile time
- ViewModelBase - Descendant view model
- have INotifyPropertyChanged Interface implementation of simple classes
The first option used in this article , Because it keeps your view model code clean 、 compact , And help you avoid spelling mistakes .
take DevExpress.Mvvm.CodeGenerators and DevExpress.WinUI NuGet Add packages to your project ( Please note that , You need to get a free quote source or install our components to access DevExpress.WinUI package ). After adding package , Create a view model class and put GenerateViewModel Attribute assigned to it :
using DevExpress.Mvvm.CodeGenerators;
[GenerateViewModel]
public partial class MainViewModel {
[GenerateProperty]
string userName;
[GenerateCommand]
void Register() {
Debug.WriteLine($"{UserName} was successfully registered!");
}
}Please note that , You need to make the class partial and add DevExpress.Mvvm.CodeGenerators Namespace .
At compile time, the generator will automatically create a INotifyPropertyChanged Supported view model counterparts :
partial class MainViewModel : INotifyPropertyChanged {
public event PropertyChangedEventHandler? PropertyChanged;
protected void RaisePropertyChanged(PropertyChangedEventArgs e) => PropertyChanged?.Invoke(this, e);
public string? UserName {
get => userName;
set {
if(EqualityComparer.Default.Equals(userName, value)) return;
userName = value;
RaisePropertyChanged(UserNameChangedEventArgs);
}
}
DelegateCommand? registerCommand;
public DelegateCommand RegisterCommand => registerCommand ??= new DelegateCommand(Register, null);
static PropertyChangedEventArgs UserNameChangedEventArgs = new PropertyChangedEventArgs(nameof(UserName));
}You can view the generated classes in the project :Dependencies -> Analyzers -> DevExpress.Mvvm.CodeGenerators -> DevExpress.Mvvm.CodeGenerators.ViewModelGenerator -> MainViewModel.g.cs

take CanRegister Method is added to your view model to determine when Register command . Please note that ,WinUI Command not to use CommandManager, So you need to use RaiseCanExecuteChanged Manually refresh CanExecute state :
public partial class MainViewModel {
//...
void OnUserNameChanged() {
RegisterCommand.RaiseCanExecuteChanged();
}
bool CanRegister() => !string.IsNullOrEmpty(UserName);
}The code generator will automatically OnUserNameChanged and CanRegister Merge into UserName Properties and Register In command .
The view model has a for storing user names UserName Properties and registered users RegisterCommand Method , Let's create a simple one UI To use the view model , Add a... To the main window TextBox And a Button And bind them to the properties and commands of the view model :
<StackPanel>
<TextBox Text="{x:Bind ViewModel.UserName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<Button Content="Register" Command="{x:Bind ViewModel.RegisterCommand}"/>
</StackPanel>You may have noticed , We used x:Bind replace Binding,x:Bind yes UWP A relatively new markup extension introduced in , It uses type information at compile time to optimize binding , So it's best to use it as much as possible . Use... In windows or user controls x:Bind when , The default binding source is the window itself , Therefore, you need to define the view model as a window property :
public sealed partial class MainWindow : Window {
public MainViewModel ViewModel { get; } = new MainViewModel();
public MainWindow() {
this.InitializeComponent();
}
}Now simply MVVM The application can send information from the view to the view model and execute the commands of the view model , Expand it to allow users to click Register Button to display a message box . Use UI service , Prevent visual elements from not being accessed directly from the view model , This will help us keep clean MVVM Pattern , take MessageBoxService Add to the view and ServiceClient Property is bound to your view model :
<Window ...
xmlns:dxc="using:DevExpress.WinUI.Core">
<StackPanel>
<dxc:Interaction.Behaviors>
<dxc:MessageBoxService ServiceClient="{x:Bind ViewModel}"/>
</dxc:Interaction.Behaviors>
<TextBox Text="{x:Bind ViewModel.UserName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<Button Content="Register" Command="{x:Bind ViewModel.RegisterCommand}"/>
</StackPanel>
</Window>then , take ImplementISupportUIServices Parameters added to GenerateViewModel Properties and in Register Method used in MessageBoxService:
using DevExpress.Mvvm;
using DevExpress.Mvvm.CodeGenerators;
[GenerateViewModel(ImplementISupportUIServices = true)]
public partial class MainViewModel {
[GenerateProperty]
string userName;
IMessageBoxService MessageBoxService { get => ServiceContainer.GetService<IMessageBoxService>(); }
[GenerateCommand]
void Register() {
MessageBoxService.ShowAsync($"{UserName} was successfully registered!", "Registration");
}
}Now? , When the user clicks the button, he will see a message box . Please note that , Your view model does not directly access any visual elements , Instead, the service mechanism is used as the middle tier .
By pressing Enter Key Register Commands to enhance the user experience ,WinUI The button doesn't have IsDefault attribute , Therefore, it is necessary to handle the key event to capture the press Enter The moment of . our MVVM The kit has KeyToCommand operation , The command can be invoked when the specified key is used . take KeyToCommand Add behavior to Interaction.Behaviors Set merge to set its KeyGesture and Command attribute :
<StackPanel>
<dxc:Interaction.Behaviors>
<dxc:KeyToCommand KeyGesture="Enter" Command="{x:Bind ViewModel.RegisterCommand}"/>
<!--...-->
</dxc:Interaction.Behaviors>
<!--...-->
</StackPanel>KeyToCommand Is an operation that can be used immediately , But you can easily create custom actions as needed , To avoid writing similar code hiding in different views .
DevExpress WPF | Download trial
DevExpress WPF Have 120+ Controls and libraries , Will help you deliver high-performance business applications that meet or exceed the needs of your enterprise . adopt DevExpress WPF Can create a powerful interactive XAML Basic applications , These applications focus on the needs of today's customers and build the next generation of touch enabled solutions . Whether it's Office Extension products of office software , Or data centric business intelligence products , Can pass. DevExpress WPF Control to implement .
DevExpress Technology exchange group 6:600715373 Welcome to group discussion
边栏推荐
- Foreign capital staged a "successful flight" and domestic capital took over the offer. Is New Oriental online "square"?
- Two problems that may occur in the use of ThreadLocal and thread pool
- 近年区域赛(20-22)
- 298th weekly match
- Notes on writing questions in C language -- find s=a+aa+aaa+aaaa+aa Value of a
- 动态规划【一】(背包问题)
- 华为又发新品?这几款功能太优秀了
- Fpga/cpld final examination paper for the first semester of Nanjing University of information technology 2020-2021
- The R language uses the DOTPLOT function of epidisplay package to visualize the frequency of data points in different intervals in the form of point graph, uses the by parameter to specify the groupin
- Guys, please ask me a question about flynk SQL. I have an FQL statement, insert into C sale
猜你喜欢

This humble doctor's thesis is very popular: looking back, I feel sorry for countless mountains

Use the uniapp framework to build the zheliban micro application (single sign on, embedded point, aging adaptation, RPC gateway)

使用uniapp框架搭建浙里办微应用(单点登录、埋点、适老化、RPC网关)

Literature analysis CiteSpace 6.1.2 download and installation tutorial

空中操作仅通过距离映射对遮挡目标进行鲁棒定位(RAL2022)

11 introduction and installation of beautiful soup parsing library

品牌、产品和服务齐发力,东风日产接下来有什么新动作?

GoF模式-03-行为型模式(下)

SQL operation: with expression and its application

Yolov5 trains its own data set to report error records
随机推荐
jvm造轮子
动态规划【一】(背包问题)
W10添加系统环境变量Path
The R language uses rbind The fill function vertically merges dataframe data of two different data columns
Technology sharing | mysql:caching_ sha2_ Password quick Q & A
文献分析 Citespace 6.1.2 下载及安装教程
The R language uses the follow up The plot function visualizes the longitudinal follow-up chart of multiple ID (case) monitoring indicators, and uses line Col parameter custom curve color (color)
在Qt中设置程序图标的方法介绍
[pwn基础]Pwntools学习
挖财商学院属于证券公司吗?开户安全吗?
How to create network redundancy for network managed national production reinforced switch
华为又发新品?这几款功能太优秀了
秒云云原生信创全兼容解决方案再升级,助力信创产业加速落地
R语言使用epiDisplay包的statStack函数基于因子变量通过分层的方式查看连续变量的统计量(均值、中位数等)以及对应的假设检验
力扣每日一练之双指针1Day8
GoF模式-03-行为型模式(下)
点歌系统也有鸿蒙版了?老王抢先体验了一把
Experience sharing of Sanye's friends: Qianqiu Shu (general manager of Qianqiu)
鸿蒙之后,华为宣布再将捐赠欧拉,鸿蒙和欧拉的捐赠预计将给业界带来哪些影响?
This humble doctor's thesis is very popular: looking back, I feel sorry for countless mountains