当前位置:网站首页>06 Maui, WPF uses MVVM toolkit framework to build MVVM program

06 Maui, WPF uses MVVM toolkit framework to build MVVM program

2022-07-19 04:12:00 Little girl

I talked about it before. ,MVVM Architecture is a design idea , Not just for WPF,MAUI, And others C# Development also applies . and MVVM Frame besides MVVM Toolkit, also MVV MLight ( Stop maintenance ),Prism wait , This chapter mainly studies Toolkit.

1. MVVM Toolkit Frame features

  • Is a lightweight and open source free MVVM frame
  • Developed and maintained by Microsoft

 2. MVVM Toolkit  Common basic types

  • ​ObservableObject All object properties must inherit from this type , And it provides SetProperty Method , Use SetProperty Method automatically notifies the front end that the properties have changed . Be careful , When the attribute value remains unchanged , The method SetProperty Not trigger , Only when the attribute value changes .
  • RelayCommand  Click event of front-end page binding command
  • AsyncRelayCommand   Asynchronous click event of front-end page binding command , The return value is Task
  • WeakReferenceMessenger News subscription
  • ObservableRecipient  News subscription
  • ​IRecipient  News subscription

 3. Next, let's introduce in WPF How to use

3.1  Create a new one WPF project ,Nuget Search for installation Microsoft.Toolkit.Mvvm

4. Implement a function , When you click the button on the page , hold TextBox The value of is sent to the background page , And bind the value back to the front page . 

  4.1 First build a class , Inherited from  ObservableObject class

1. The shortcut to creating a complete attribute is to enter propfull Press two times. Tab

2.  You have to set SetProperty Method . When the attribute value changes , Inform the front .

    The original way of writing  

The third party MVVM In the frame ObservableObject Is to implement the INotifyPropertyChanged and INotifyPropertyChanging Interface base class .  So the principle of native writing and third-party writing is not much different .

4.2 stay  S71200ViewModel Class , Add a command , And instantiate .

  Synchronization method , You can also change the asynchronous way

4.3 Front end component page

  1. Use Binding Is a fixed grammar , Bind the properties of the background
  2. Binding mode ,model It's a (mode) Is the type of enumeration , Altogether 5 A species
    2.1 OneWay( Update the target attribute when the source changes )
    2.2 TwoWay( Source change updates target and target change updates source )
    2.3 OneTime( Set the target only according to the source , It won't change in the future )
    2.4 OneWayToSource( And OneWay contrary )
    2.5 Default Default ( It can be one-way or two-way , It depends on whether the valued source or target has get or set Designated )
  3. UpdateSourceTrigger attribute , because WPF in , about TextBox, except Text All attribute sources other than attributes will be updated immediately as the attributes change ; however Text Properties are different , It is updated only after the target element is out of focus . So if you want to make TextBox Changes in are immediately transmitted to the source , You need to set UpdateSourceTrigger To control . If this property is not set , The value obtained in the background is null .

Reference resources : The literature 1, The literature 2

4.4 hold S71200ViewModel Associate with the page

 

4.5  Test verification , When you click the page button , Trigger the command .

 4.6  Another way to get the front page value , But this way is different from MVVM irrelevant , You can also get TextBox The value of the input ,

4.7  Native implementation of button events

 4.8  How to get the value in the background , open .cs Class file

 4.9  Address yes TextBox Defined Name, A random name . Go to the background to get the value entered by the foreground .

 5. Message subscription  WeakReferenceMessenger

5.1 How to publish messages

// string  The type of message published 
WeakReferenceMessenger.Default.Sen<string>(" It's me who posted it ");

5.2 How to subscribe to publish messages

5.2.1 Subscribe to published messages through anonymous methods

// subscribe 
WeakReferenceMessenger.Default.Register<string>(this,method);
//string  It is the data type passed during subscription 
// this  Point to the currently used class 

// Subscription method 
public void method(object obj,string msg){

// msg  Data received 
}

Be careful : Among the published message types , If the release is string type , All subscribed string Type of message , Can receive all published string Type of message .

5.2.2 By designation  token To publish the specified message

WeakReferenceMessenger.Default.Send<string,string>(" Message sent ", "token");

5.2.3  And only receive fixed when subscribing token Published messages

// subscribe , the second  string  Namely  token
WeakReferenceMessenger.Default.Register<string,string>(this,"token",method);
//string  It is the data type passed during subscription 
// this  Point to the currently used class 

// Subscription method 
public void method(object obj,string msg){

// msg  Data received 
}

 6.  Message subscription  ObservableRecipient,​IRecipient 

6.1 In the class to implement message subscription or publishing , Realization ObservableRecipient The type and IRecipient  Interface

 6.2 Currently, I have released a string Type of message

WeakReferenceMessenger.Default.Sen<string>(" Release the news ");

6.3 Then the implementation method can get the published string Type of message

Be careful , Want messages to be subscribed , To put IsActive assignment by true Talent

6.4 News subscription and release , You can also publish and subscribe through different objects .

for example , Currently, I subscribe to this message , Just want to subscribe to a certain class , Don't want it to subscribe to all string Type of message

The release can be written like this

WeakReferenceMessenger.Default.Send< Object class >();

Subscriptions can be specified in this way

 

In this way, you can subscribe to the specified object to publish the message content , Not all of them will subscribe to .

 7. IOC Inject , At present, this framework does not provide , But it can be done in other ways ico Handle

1. Why use ioc, For example, at present, we need to write a data interface for the page to adjust data , Anyway, some interface data services , Data operation, etc

7.1 for example , Currently, establish an interface service class , Used for data operation

7.2 Then inside the class , By injection , Use this interface for data operation

 7.3 If you want to be the same as above , stay wpf Use ioc Inject , That should be handled like this .

First of all Nuget Install a library , This library can support ioc Injected Library

 

7.4 After installation , Initialization required . Mainly this kind of treatment ioc The library of , Its life cycle must be synchronized with our application , So you need to initialize the application , This ioc Containers should also be initialized

 7.5  In the initialization method , For interface registration

 7.6 After writing this way , Due to the previous use of mvvm When initializing binding in , It was written like this before

this.DataContext=new MainWindowViewModel();

  But now it needs to be changed to this , You need to put this MainWindowViewModel Sign up to ioc In the container

  Then it will look like this when initializing the binding , adopt Services To get

this.DataContext=App.Current.Services.GetService(typeof(MainWindowViewModel));

Container initialization code

  public partial class App : Application
    {
        public App()
        {
            Services = GetService();
        }
        public new static App Current => (App)(Application.Current);

        public IServiceProvider Services {get;}
        public static IServiceProvider GetService()
        {
            var services = new ServiceCollection();
            services.AddSingleton<IValueInterface, ValueInterface>();
            services.AddScoped<MainWindowViewModel>();
            return services.BuildServiceProvider();

        }
    }

Content from :【2022 The whole net starts 】WPF Light class in application development MVVM frame -MVVM Toolkit The source code is attached to the tutorial B0560_ Bili, Bili _bilibili

I suggest you watch the video directly , After all, I just record the learning process . 

原网站

版权声明
本文为[Little girl]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/200/202207170332454588.html