Starting with Prism learn WPF (v) MVVM (a) ViewModel?

Source: Internet
Author: User

Starting from Prism learn WPF (v) MVVM (a) ViewModel?

Start learning WPF (i) WPF from Prism?

Learn WPF from Prism (ii) prism?

Learn WPF (iii) prism-region from Prism?

Start learning WPF (iv) Prism-module from Prism?

Starting with Prism learn WPF (v) MVVM (a) ViewModel?

Starting with Prism learn WPF (vi) MVVM (ii) Command?

Start with Prism learn WPF (vii) MVVM (iii) event aggregator Eventaggregator?

0x5 MVVM

Clam, and finally to MVVM. In particular, the previous module, it is difficult to write, anyway, probably know how to use the good, specific how a container, how to rely on injection, I am not very understanding, prism heavy dependence on the container, which is, which is dependent on container injection.

So far, we have known how to set up region, how to relate view, and relate the view in other module. So next is MVVM,★,°:. ☆ ( ̄▽ ̄)/$:. °★ .

First look at how wikis are defined for MVVM:

MVVM(Model–view–viewmodel) is a software architecture pattern.

MVVM helps to separate the development of the graphical user interface from the development of business logic or back-end logic (the data Model ), which is achieved through the placement language or GUI code. The view model of MVVM is a value converter, [1] which means that the view model is responsible for exposing (transforming) data objects from the model for easy management and rendering of objects. In this respect, the view model does more than the view and handles the display logic for most of the views. [1] The view model can implement the mediator pattern and organize access to the back-end logic of the set of use cases supported by the image.

Dior not Dior? First of all, he's not WPF proprietary, and now many front-end frameworks implement the MVVM pattern, like vue,angular. What kind of magical place does he have in the way that MVVM is so hot? data bidirectional binding ! data bidirectional binding ! data bidirectional binding !

When I first looked for the MVVM framework, I actually did not care about decoupling, the front-end separation, what to test, I just had enough of the WinForms foreground code in ShowDetails and Setmodel, later found that MVVM can achieve two-way binding, data-driven interface display, the fans (? 艸 '?). So far, let's see prism, how to achieve MVVM.

ViewModel and positioning what is the role Viewmodel,viewmodel plays in MVVM?

ViewModel is the corresponding view (data and behavior) of the abstract, view is only a ViewModel consumer, then there are other consumers? Of course, that's the unit test, which is said later. ViewModel provides the data context for the view (DataContext), simply put, the things you need to show in your view are here, and you need to bind with me, including data and commands, otherwise you're a static.

How do you specify ViewModel for a view, typically we specify DataContext for the control, and Prism provides us with a simpler way to contract .

Binding method of the contract
    • Step1 Create a new WPF project, create a new two folder views and ViewModels to store the view and ViewModel, delete the MainWindow.xaml, and create a new MainWindow form when our shell. Delete App.xaml StartupUri , new Bootstrapper.cs , this is one of the most common bootstrapper:
using Microsoft.Practices.Unity;using Prism.Unity;using ViewModelLocator.Views;using System.Windows;namespace ViewModelLocator{    class Bootstrapper : UnityBootstrapper    {        protected override DependencyObject CreateShell()        {            return Container.Resolve<MainWindow>();        }        protected override void InitializeShell()        {            Application.Current.MainWindow.Show();        }    }}
    • STEP2 New in the ViewModels folder, a Mainviewmodel class, Inherit bindablebase, note, here is a class (class)

MainWindowViewModel.cs

using Prism.Mvvm;namespace ViewModelLocator.ViewModels{    public class MainWindowViewModel : BindableBase    {        private string _title = "Prism Unity Application";        public string Title        {            get { return _title; }            set { SetProperty(ref _title, value); }        }        public MainWindowViewModel()        {        }    }}
    • Step3 Modify MainWindow.xaml , overwrite the following code: (currently also can not overwrite, compare found, we here only a little more things)
<Window x:Class="ViewModelLocator.Views.MainWindow"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        xmlns:prism="http://prismlibrary.com/"        prism:ViewModelLocator.AutoWireViewModel="True"                Title="{Binding Title}" Height="350" Width="525">    <Grid>        <ContentControl prism:RegionManager.RegionName="ContentRegion" />    </Grid></Window>

Tips: Data binding title= "{Binding title}", Title is an open attribute in the corresponding viewmodel.

After the run found, the window title of the official Mainwindowviewmodel title value, but we did not specify for MainWindow ViewModel Ah, normal binding seems to be the case

    <UserControl.DataContext>        <vm:NumberChangeLogViewModel />    </UserControl.DataContext>

Or so

<vw:NumberView             DockPanel.Dock="Top"             DataContext="{Binding Path=Number, Mode=OneTime}"             />

Clam, at first I was also very confused, but I love learning, in the prism of the source code Prism.Mvvm.ViewModelLocationProvider I found this:

        <summary>//Viewmodelfactory that provides the View instance and ViewModel type as parameters.        </summary> static Func<object, Type, object> _defaultviewmodelfactorywithviewparameter; <summary>///Default view type to view model type resolver, assumes the view model was in same ASSEMB        Ly as the view type, but the "ViewModels" namespace. </summary> static Func<type, type> _defaultviewtypetoviewmodeltyperesolver = ViewType =&            Gt                {var viewName = Viewtype.fullname; ViewName = Viewname.replace (". Views. ",".                ViewModels. "); var viewassemblyname = Viewtype.gettypeinfo ().                Assembly.fullname; var suffix = viewname.endswith ("View")?                "Model": "ViewModel";                var viewmodelname = String.Format (CultureInfo.InvariantCulture, "{0}{1}, {2}", ViewName, suffix, viewassemblyname); Return TYpe.            GetType (Viewmodelname); };

Is it enlightened?

In the end, your program directory is like this:

We're different. Custom conventions

The Convention is to be broken, someone may think that the suffix plus a viewmodel is really lowb, I want to change him, can not? Of course it's wide.

Intimate bootstrapper provides us with a overridable Configureviewmodellocator method to configure the ViewModel locator, if you want to modify the default convention for the view after the name +VM, you can Bootstrapper.cs write in this:

        protected override void ConfigureViewModelLocator()        {            base.ConfigureViewModelLocator();            ViewModelLocationProvider.SetDefaultViewTypeToViewModelTypeResolver((viewType) =>            {                var viewName = viewType.FullName;                var viewAssemblyName = viewType.GetTypeInfo().Assembly.FullName;                var viewModelName = $"{viewName}VM, {viewAssemblyName}";                return Type.GetType(viewModelName);            });        }
I am me, the color is not the same fireworks

There is no shortage of personalities in this world, and your agreements and breaking promises are not all tarred with. I'm going to be different, who I want to tie with. Well, who you are with is your freedom, prism cannot limit you, or you will complain that it is undemocratic.

If you want to specify the ViewModel object you are bound to and do not want to follow certain rules, you can also register bindings in the Configureviewmodellocator method, like this:

       protected override void ConfigureViewModelLocator()        {            base.ConfigureViewModelLocator();            // type / type            //ViewModelLocationProvider.Register(typeof(MainWindow).ToString(), typeof(CustomViewModel));            // type / factory            //ViewModelLocationProvider.Register(typeof(MainWindow).ToString(), () => Container.Resolve<CustomViewModel>());            // generic factory            //ViewModelLocationProvider.Register<MainWindow>(() => Container.Resolve<CustomViewModel>());            // generic type            ViewModelLocationProvider.Register<MainWindow, CustomViewModel>();        }

Of course, in XAML,

prism:ViewModelLocator.AutoWireViewModel="True"

is still essential.

Learn WPF from Prism (v) MVVM (i) ViewModel?

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.