当前位置:网站首页>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-07-27 03:06:00 【Interface development Starling】
In this paper , We will describe how to create from scratch WinUI MVVM Applications , And show in the process DevExpress WinUI MVVM The powerful functions of the framework .
first , The official technical team is 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 migrate the framework there . stay v22.1 in , Official team for WinUI To optimize the MVVM frame , Keep the core functionality intact , If you use our WPF or WinForms Control , Migrating to WinUI I don't have any problems with it .
DevExpress WPF v22.1 Official download
Let's start by creating a 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 avoid spelling mistakes .
take DevExpress.Mvvm.CodeGenerators and DevExpress.WinUI NuGet Add packages to your project , After adding the 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 , Create a simple 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 , In this article, I 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 , Visual elements can be accessed without 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 .
Let's press 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 . but MVVM The kit has KeyToCommand Behavior , 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 behaviors 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
边栏推荐
- I heard that you knelt on the interface test during the interview?
- 手动从0搭建ABP框架-ABP官方完整解决方案和手动搭建简化解决方案实践
- [binary search simple question] leetcode 35. search insertion position, 69. Square root of X, 367. Effective complete square, 441. Arrange coins
- idea中常用的快捷键
- [simple question of stack and queue] leetcode 232. realize queue with stack, 225. realize stack with queue
- vs2019 中编译和使用 protobuf 库
- 素因子分解--C(gcc)--PTA
- #博客大赛# 斗胆尝试浅入门之BAC
- Rust web (I) -- self built TCP server
- Arduino UNO +74hc164 water lamp example
猜你喜欢

Favicon网页收藏图标在线制作PHP网站源码/ICO图片在线生成/支持多种图片格式转换

阿里云技术专家杨泽强:弹性计算云上可观测能力的构建

商城小程序项目完整源码(微信小程序)

次轮Okaleido Tiger即将登录Binance NFT,引发社区热议

CS224W fall 1.2 Applications of Graph ML
The most complete basic knowledge of software testing in the whole network (a must for beginners)

What is a process?

Goatgui invites you to attend a machine learning seminar

如何使用DevExpress WPF在WinUI中创建第一个MVVM应用程序?

CuteOne:一款OneDrive多网盘挂载程序/带会员/同步等功能
随机推荐
Getlocation:fail the API need to be declared in the requiredprivateinfo field in app.json
数据资产管理的概念
MarqueeView实现滑动展示效果
单例模式(双检锁)
Inftnews | "traffic + experience" white lining e Digital Fashion Festival leads the new changes of digital fashion
如何使用DevExpress WPF在WinUI中创建第一个MVVM应用程序?
Play a parallel multithreaded mcu-mc3172
Favicon网页收藏图标在线制作PHP网站源码/ICO图片在线生成/支持多种图片格式转换
论构造函数的原型是谁
#博客大赛# 斗胆尝试浅入门之BAC
Why do people like to rank things
Okaleido tiger logged into binance NFT on July 27, and has achieved good results in the first round
setTimeout第一个参数应该注意的地方
typora详细教程
Thread.Sleep(0)的作用
Cs224w fall course - --- 1.1 why graphs?
Kubernetes Dashboard 部署应用以及访问
Function stack frame explanation
What is a process?
CS224W fall 1.2 Applications of Graph ML