WPF-MVVM pattern study notes 3 - MVVM concept digging again

     By last article < WPF-MVVM pattern study notes 2 - MVVM simple example > in the cited an example, I have a MVVM probably relatively plain meaning. At the same time, people who read the previous two articles, I also know that most of this series of articles from other blog, I really just played a summary of the role, after all, I was learning, e-learning is certainly going on others notes myself. This article will Reviewing the Old way again to understand MVVM, MVVM again sought the understanding of a deep level.

1. Look "MV-VM"

    M: That Model, model abstracted from the real world.

    V: i.e. View, View, interface that interacts with the user input device.

How 2.View interact with the Model?

    At this time, the Binding can play a role, such as one of the text box and the text in the Model View "user name" in association, users can be accessed and modified by the operation of the Model text box "User Name" a. But in the actual programming, we find that property (or method) Model is often not so easy to be associated with the View interface controls. For example, the definition of the class Time a time, the time class Time has year, month, day three properties, as follows

   

    public class Time
    {
        private string year;
        public string Year
        {
            get
            {
                return this.year;
            }
            set
            {
                this.year = value;
            }
        }


        private string month;
        public string Month
        {
            get
            {
                return this.month;
            }
            set
            {
                this.month = value;
            }
        }


        private string day;
        public string Day
        {
            get
            {
                return this.day;
            }
            set
            {
                this.day = value;
            }
        }

        public Time(string year, string month, string day)
        {
            this.year = year;
            this.month = month;
            this.day = day;
        }
    }


   As well as an interface that TimeView, as follows

   

   I want to achieve press button 1 time in years - to show the form of day - month; press the button 2, the time in months - in the form of show - day. In this case it is necessary to make some "extra operation", i.e., the data model in Time after some additional processing can be passed to view, and vice versa. Now, we realize this View seems to require a "Helper" class to handle some extra work. Helper contains the code can be placed Model (e.g. where Time) in many places outside, such as in the corresponding View.cs. And I really do before, the vast majority of processing logic on the so-called CodeBehind in.

3. Later ...

   Later, in various design patterns books are seen, in order to peel off View and Model, View achieve an alternative, there was the MVC. After With MVC, I began to have MVP, MVVM and so on MV-XX. But almost (I add a little of it, because the other design patterns I have no contact with) all of these design patterns are mainly around two issues:

   First, the relationship between the Model and View, completely isolated? One-way or two-way?

   Second, the "XX" which features need to complete a simple process scheduler? Complicated rules processing?

   These issues are not related, whether to adopt a pattern depending on your development environment in which (such as language features, frame characteristics) and the characteristics of your business and the main point of change, and so face.

4. But ...

   But with MVC, MVP of the difference is that not only the introduction of technical reasons MVVM (decoupled respond to changes cliché), another big reason: to change the way the software development team. We need a way to code logic View layer extracted, and the View layer is very pure in order to build it entirely to art. Accordingly ,, View respective logical layer needs to be drawn into a layer of code to allow a programmer to focus here. This requires:

   ① you have the ability of using Blend and other XAML tools for programmers output of artists, he focused on pure UI / UE, he also must have a certain "programmer" thinking, in order to output something well as a program part of running, rather than just "looks" is so;

   You need to be able ② from programmer View layer but can still write high-quality code.

5. Binding、Command、AttachBehavior

   Recall that the reason why we want to write some code (C #) in View (Xaml) behind, was simply trying to pass some data processing and transfer of data when the data or perform some action when the user interacts with the interface controls. The simplest example is the View Controler to calling a method in the interface when the MVC when interaction occurs, so that the corresponding operation "indicates" transmitted to "background" go. In the prior art, such a "bridging" code is necessary. In WPF, it may be "engagement" between the layers by another technique, which is "the Binding" and "the Command", and "attachBehavior."

   By Binding, we can pass data to achieve; through Command, we can invoke operations implementation. Binding and Command is written in XAML, so it seems behind the XAML file for the CS can be completely abandoned or ignored, and this is the art of XAML files needed. For these definitions describe Binding and Command and other relevant information of the code should be placed there, of course, it is not a View, but not the Model, is "ViewModel". View ViewModel for this are tailor-made, which contains the relevant information needed to Binding, and the provision of such Converter DataContext to View of Binding, it contains a definition for Command View layer can be used directly, in addition, it is a variant the Controler, it was responsible for the scheduling of business processes.

   

   The figure is very intuitive display View \ ViewModel \ Model of interaction diagram, really admire draw the author of this picture, too straightforward.

   So AttachBehavior what is it? Using the WPF properties Command, Binding, AttachProperty the like under normal circumstances, can work well with between View and ViewModel. Suppose we have a Button, the Button is clicked when we want to perform some action, quite simply, the operating encapsulated into a Command and bound to the Button on it. But if we want to perform some other operations at the time it was Load Button's? Since the Command Button is not directly triggered by the Load event, so you can not use the Command. You can not write directly to the Load event handler in Xaml Button where the corresponding CS document, and which we have just MVVM design is contradictory. Is not a good solution is to inherit what Button, and wrote a triggered by the Load Command, this is possible, but obviously not good, as a control does not have a property and inheritance and without the use of AttachProperty, we can using attachBehavior.

6. ending

    Here, I understand MVVM, but also know the role of the ViewModel, so long you can use this model to solve the above problem of the time display,


   Add Class TimeViewModel, as follows

   

    public class TimeViewModel : NotificationObject
    {
        private Time time;
        public Time Time
        {
            get
            {
                return this.time;
            }
            set
            {
                this.time = value;
                this.RaisePropertyChanged(() => this.time);
            }
        }

        public TimeViewModel()
        {
            time = new Time("1991","02","23");
            birthday = time.Year + "-" + time.Month + "-" + time.Day;
        }

        private string birthday;
        public string Birthday
        {
            get
            {
                return this.birthday;
            }
            set
            {
                this.birthday = value;
                this.RaisePropertyChanged("Birthday");
            }
        }


        public bool CanSubmit
        {
            get
            {
                return true;
            }
        }

        public void Submit1()
        {
            Birthday = time.Year + "-" + time.Month + "-" + time.Day;
        }

        public void Submit2()
        {
            Birthday = time.Month + "-" + time.Day + "-" + time.Year;
        }

    }
   In this ViewModel, the definition of a string Birthday date format for display, while the two methods Submit1 () and Submit2 () are two buttons Click event bindings.

   At this time, the content view View

<UserControl x:Class="MVVMDemo.View.TimeView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 
             xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" 
             xmlns:vm="clr-namespace:MVVMDemo.ViewModel"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="400">
    <Grid x:Name="gridLayout">
        <Grid.DataContext>
            <vm:TimeViewModel />
        </Grid.DataContext>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="5*" />
            <ColumnDefinition Width="5*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="5*" />
            <RowDefinition Height="5*" />
            <RowDefinition Height="5*" />
            <RowDefinition Height="5*" />
        </Grid.RowDefinitions>

        <TextBlock Text="Time:" Grid.Row="0" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Center"/>
        <TextBlock Text="{Binding Path=Birthday,Mode=Default}" Grid.Row="0" Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Left"/>

        <Button x:Name="Btn1" Content="按钮1:年-月-日"  IsEnabled="{Binding CanSubmit}"  Grid.Row="2" Grid.Column="0" Width="150" Height="50" VerticalAlignment="Center" HorizontalAlignment="Right">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <ei:CallMethodAction TargetObject="{Binding}" MethodName="Submit1"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </Button>

        <Button x:Name="Btn2" Content="按钮2:月-日-年"  IsEnabled="{Binding CanSubmit}"  Grid.Row="2" Grid.Column="1" Width="150" Height="50" VerticalAlignment="Center" HorizontalAlignment="Right">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <ei:CallMethodAction TargetObject="{Binding}" MethodName="Submit2"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </Button>
    </Grid>
</UserControl>

  Compile and run the program (the project Click here to download )

       

(2.23 my birthday is coming up, do not know no one will remember, huh, huh)

Article Source

http://www.csdn123.com/itweb.php?url=aHR0cDovL3d3dy5jbmJsb2dzLmNvbS9XaW5kb3dzLXBob25lL2FyY2hpdmUvMjAxMy8wOC8yNC8zMTE1ODIzLmh0bWw=

Thank my friend! ! You said very easy to understand! !

发布了143 篇原创文章 · 获赞 161 · 访问量 121万+

Guess you like

Origin blog.csdn.net/mybelief321/article/details/44459535