当前位置:网站首页>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 :

  1. View model generated at compile time
  2. ViewModelBase - Descendant view model
  3. 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

more DevExpress Online open class 、 For Chinese tutorial information, please go to the Chinese website

 

原网站

版权声明
本文为[Interface development Starling]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211759316936.html