Silverlight實用竅門系列:52.Silverlight中的MVVM框架極速入門(以MVVM Light Toolkit爲例)

    在本文將以MVVM Light Toolkit爲例講解MVVM框架在現實中的使用入門,首先我們在http://mvvmlight.codeplex.com/下載它的MVVM框架下來。也可以通過 http://files.cnblogs.com/chengxingliang/GalaSoft.MvvmLight.V3.rar 下載MVVM Light Toolkit。然後我們安裝這個安裝包,然後重新打開VS2010,新建一個項目,如下圖所示:

   Tip:MVVM分爲Model、ViewMode、View三層。

        •Model是實體類層,它存放所有需要用到的實體類。

        •ViewMode層是邏輯層,操作所有Model層和View界面層的邏輯運算並且作爲一個大的實體類,提供屬性綁定到View層上面去。

        •View層是界面顯示層,只需要它的Xaml代碼去綁定相應的ViewMode層的屬性即可。

        下面我們來看新建成功的項目結構如下:

        一、在這裏我們先來看MainPage.xaml中的代碼,在這裏綁定的MainPage.xaml是View層,它綁定上了ViewModel層,也就是MainViewModel.cs類

<UserControl x:Class="MvvmLight1.MainPage"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             Height="300"
             Width="300"
             DataContext="{Binding Main, Source={StaticResource Locator}}">
    <!--在這裏綁定App.xaml中的靜態資源,以連接MainViewModel類(ViewMode層)  MainPage.xaml代碼爲View層-->
    
    
    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Skins/MainSkin.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>

    <Grid x:Name="LayoutRoot">

        <TextBlock FontSize="36"
                   FontWeight="Bold"
                   Foreground="Purple"
                   Text="{Binding Welcome}"
                   VerticalAlignment="Center"
                   HorizontalAlignment="Center"
                   TextWrapping="Wrap" Margin="12,25,20,171" />
        <Button Content="{Binding BtnContent}" Height="23" HorizontalAlignment="Left" Margin="12,178,0,0"
                Command="{Binding ShowMessage}" Name="button1" VerticalAlignment="Top" Width="75" />
        <Button Content="點我改變文字" Height="23" HorizontalAlignment="Left" Command="{Binding ChangeText}"
                Margin="187,178,0,0" Name="button2" VerticalAlignment="Top" Width="75" />
    </Grid>
</UserControl>

        二、然後我們看ViewModel層,在這裏我們申明瞭一些string屬性以綁定到View層得顯示內容上,然後對於鼠標的點擊事件採用Command命令傳遞事件和處理方法,並且設置綁定。這樣我們可以直接將前臺的點擊事件等和後臺分離,並且我們可以繼承INotifyPropertyChanged接口,以讓ViewModel層的屬性被改變的時候,也反映到View層,在Command方法中改變ViewModel層的屬性即可改變View層的前臺顯示。其具體的詳解在下面的代碼中已經給出。

using GalaSoft.MvvmLight;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;
using System.Windows;
using System.ComponentModel;

namespace MvvmLight1.ViewModel
{
    /// <summary>
    /// This class contains properties that the main View can data bind to.
    /// <para>
    /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
    /// </para>
    /// <para>
    /// You can also use Blend to data bind with the tool's support.
    /// </para>
    /// <para>
    /// See http://www.galasoft.ch/mvvm/getstarted
    /// </para>
    /// </summary>
    public class MainViewModel : ViewModelBase, INotifyPropertyChanged
    {
        public string Welcome
        {
            get
            {
                return "歡迎使用MVVM Light! ";
            }
        }

        /// <summary>
        /// 類初始化
        /// </summary>
        public MainViewModel()
        {
            _btnContent = "點擊我";
            RegistCommand();
        }

        //A.對於屬性的綁定
        private string _btnContent;
        public string BtnContent
        {
            set
            {
                _btnContent = value;
                NotifyPropertyChanged("BtnContent");

            }
            get
            {
                return _btnContent;
            }
        }

        //B.1申明對於點擊事件的綁定
        public RelayCommand ShowMessage { get; set; }
        //使用C步驟的註冊,將Command和需要運行的方法聯繫起來。
        private void showmsg()
        {
            MessageBox.Show("你成功的將命令綁定到界面層!");
        }

        //B.2改變界面上的控件顯示文字
        public RelayCommand ChangeText { get; set; }
        //執行改變文字操作
        private void changeTxt()
        {
            BtnContent = "我已經被改變了";
        }
        //是否可以改變文字
        private bool canchangeTxt()
        {
            if (BtnContent == "點擊我")
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        //C.對於所有的事件進行註冊
        private void RegistCommand()
        {
            //C.1指定需要執行的函數showmsg()
            ShowMessage = new RelayCommand(() => showmsg());
            //先執行canchangeTxt()函數,驗證是否可以改變文字,如果可以改變則執行changeTxt()函數
            ChangeText = new RelayCommand(() => changeTxt(), () => canchangeTxt());
        }

        
        public event PropertyChangedEventHandler PropertyChanged;
        public void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

    }
}

        三、在這裏我們沒有使用到Model層,它用於構造實體集合以綁定諸如DataGrid之類的控件。

        最後我們來看實例的運行效果如下,如需源碼請點擊 MvvmLight1.rar 下載。 

出處:http://www.cnblogs.com/chengxingliang/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章