WPF: WpfWindowToolkit introduces a window operation library,

Source: Internet
Author: User

WPF: WpfWindowToolkit introduces a window operation library,

The MVVM framework can greatly improve the software testability and maintainability during the development of XAML applications. The core idea of MVVM is separation of focus, which separates the business logic from the View into the ViewModel and Model. Logically speaking, this is also the location where the business logic should be located.

Specifically, MVVM can be easily implemented on the XAML platform by means of the mechanisms provided by these XAML platforms, such as Data Binding and Command. However, if you have some experience in XAML application development and MVVM usage, you will find that MVVM alone cannot solve all problems, for example, page navigation, pop-up dialog box, window operations, etc. In this case, you need to combine some technologies related to it, such as messages, behaviors, services, and dependency injection. This is because MVVM mainly targets View content, rather than View operations or other things. Therefore, operations such as pop-up windows or page navigation require the cooperation of the above technologies.

More specifically, in the development of WPF applications, we often need to open and close windows. It is not easy to implement it in the "MVVM mode. Of course, we can use messages to solve this problem. However, using messages too much will make the code difficult to maintain and increase the difficulty of debugging.

This article mainly solves this problem by sharing a Class Library:WpfWindowToolkitAs shown in the name, it is a set of Operation classes for Windows.

I. Basic Introduction

From the introduction, we can see that it can solve the problem of opening and closing windows, as well as passing parameters and return values among windows, to achieve this, you do not need to write any code in the CodeBehind of the View, nor use the message. The modifications you need are only in the XAML code and ViewModel, in this way, the MVVM principles are followed and the goal is achieved.

After downloading the source code from Github (http://github.com/imnbwd/WpfWindowToolkit), there is a Demo, through which we can see how it works. In the following content, we first have some knowledge about it. For more details, we can refer to its source code and Demo.

Ii. Installation

To use it in a project, you can download it from Nuget or directly use the following command:

InstallPackage WpfWindowToolkit
Iii. How to Use1. Open a window

There are two ways: using additional attributes or actions.

You must add a namespace before using it:

    xmlns:behaviors="clr-namespace:PraiseHim.Rejoice.WpfWindowToolkit.Behaviors;assembly=WpfWindowToolkit"    xmlns:helpers="clr-namespace:PraiseHim.Rejoice.WpfWindowToolkit.Helpers;assembly=WpfWindowToolk

Additional attributes:

    <Button x:Name="btn1"        helpers:WindowHelper.OpenWindowType="{x:Type local:Window1}"        Content="Open window using Window Helper" />

Behavior:

    <Button x:Name="btn5"        Margin="0,5,0,0"        Content="Open window with parameter using action">        <i:Interaction.Triggers>            <i:EventTrigger EventName="Click">                 <behaviors:OpenWindowAction Parameter="WPF (action)" WindowType="{x:Type local:Window1}" />             </i:EventTrigger>        </i:Interaction.Triggers>    </Button>

We can see that they are all specified to the WindowType attribute through the Type of the window to be opened.

2. Pass parameters when opening the window

It is easy to pass parameters to the ViewModel while opening the window. The same as above, you only need to assign a value to the Parameter attribute. This Parameter can be bound to the ViewModel member of the current window. Therefore, any type of data can be passed to the window to be opened.

Next, you should note that you should make some modifications to the ViewModel of the window to be opened: Make it inherit ViewModelBaseData <T>, where T is the type of the parameter passed. Then, the passed parameters can be obtained through the InternalData attribute.

    <behaviors:OpenWindowAction Parameter="WPF (action)" WindowType="{x:Type local:Window1}" />
    public class Window1ViewModel : ViewModelBaseData<string>    {           protected override string InternalData { get; set; }        ...    }

There is also a complicated way to open the window, and it also gives users more flexible control. The method is to inherit the ViewModelBaseEx class from the current window and then call its ShowWindow method. Here, we will not go into detail. For details, refer to the instructions on Github.

3. return values from the Opened Window

Two steps are required to close the Opened Window. First, the ViewModel of the first window (the window in which other windows are to be opened) must inherit ViewModelBaseEx, or ViewModelBaseEx <T> class, and then use the ShowWindow (openjavaswinfo, Action <TReturnValue>) method to open the window. The second parameter is an Action with parameters. Here the parameter is the return value, in this Action, we can process the returned value.

    public class ReturnValueMainWindowViewModel : ViewModelBaseEx<Friend>    {        public void ShowFriendSelectionWindow()        {            this.ShowWindow(new OpenWindowInfo { WindowType = typeof(ReturnValueTestWindow) }, friend =>            {                if (friend != null)                {                    MessageBox.Show($"You have selected this friend: {friend.Name}");                }                else                {                    MessageBox.Show("No friend has been selected");                }            });        }    }

Step 2: The ViewModel of the window to be opened must implement the IWindowReturnValue <T> interface. This interface contains the ReturnValue attribute. You only need to assign a value to it.

    public class ReturnValueTestWindowViewModel : BindableBase, IWindowReturnValue<Friend>    {        ...        public void SetReturnValue()         {            ReturnValue = SelectedFriend;        }        ...    }
4. Close the window

Close in View

To close the window, you can use CloseWindowAction as follows:

    <Button Content="Close the current window with confirmation">        <i:Interaction.Triggers>            <i:EventTrigger EventName="Click">                <behaviors:CloseWindowAction ClosingCheckFunc="{Binding CheckBeforeCloseWindow}" />            </i:EventTrigger>        </i:Interaction.Triggers>    </Button>

It provides the ClosingCheckFunc attribute and can be bound to a function that returns a Boolean value. If this function returns true, It is disabled. Otherwise, it is not disabled.

 Process Window. Closing events

In addition, when the Window is closed, it also provides support for the Window Closing event. Generally, we may ask whether to close the Window in the event processing. To do this, you only need to add an action for the current window, as shown below:

    <i:Interaction.Behaviors>        <behaviors:ClosingWindowBehavior ClosingCheckFunc="{Binding CheckBeforeCloseWindow}" />    </i:Interaction.Behaviors>

The method pointed to by the ClosingCheckFunc attribute is the judgment logic we added in ViewModel.

Close the window in ViewModel

In addition, it supports closing the current window in ViewModel. First, add a behavior for the window:

    <Window>        <i:Interaction.Behaviors>            <behavior:EnableWindowCloseBehavior />        </i:Interaction.Behaviors>    ...    </Window>

Then, ViewModel needs to implement the IClosable interface, which contains an Action named CloseAction and can call CloseAction in a proper position.

    public class CloseTestViewModel : BindableBase, IClosable    {        public Action CloseWindow { get; set; }        ...    }
   CloseWindow?.Invoke();  // or just CloseWindow();
Summary

This article mainly introduces the use of WpfWindowToolkit, a Windows Operating library for WPF. It fully supports MVVM and can solve the problems of opening and closing windows, passing values between windows and returning values. If you are developing a WPF Application and adopt the MVVM mode, try this library. To learn more, you can download the source code from Github.

If you have any questions or suggestions, feel free to contact us.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.