今天學習MVVM架構中“屬性”的添加並調用,特記錄如下,學習資料均來自於網絡,特別感謝翁智華的利刃 MVVMLight系列。
一個窗口的基本模型如下:
View(視圖) -> ViewModel (視圖模型)-> 多個Model(模型)
注:
- 視圖是用戶在屏幕上看到的結構、布局和外觀(UI)
- 視圖模型是暴露公共屬性和命令的視圖的抽象。在視圖模型中,綁定器在視圖和數據綁定器之間進行通信。
- 模型是指代表真實狀態內容的領域模型(面向對象),或指代表內容的數據訪問層(以數據為中心)。
下面開始學習最基礎的寫法
1、新建一個Model
public class WelcomeModel : ObservableObject { private String introduction; /// <summary> /// 歡迎詞 /// </summary> public String Introduction { get { return introduction; } set { introduction = value; RaisePropertyChanged(() => Introduction); } } }
- 這個Model繼承了一個父類:ObservableObject,這個父類的作用就是保證能夠檢測屬性是否被改變。它實現了INotifyPropertyChanged接口,通過觸發PropertyChanged事件達到通知UI更改的目的;
- 實體里面定義的每個屬性都加上RaisePropertyChanged(PropertyName)的調用,就可以實現對UI的交互更新了。
public class WelcomeViewModel : ViewModelBase { /// <summary> /// 構造函數 /// </summary> public WelcomeViewModel() { Welcome = new WelcomeModel() { Introduction = "Hello World!" }; } #region 屬性 private WelcomeModel welcome; /// <summary> /// 歡迎詞屬性 /// </summary> public WelcomeModel Welcome { get { return welcome; } set { welcome = value; RaisePropertyChanged(() => Welcome); } } #endregion }
<Window x:Class="Pvd.View.WelcomeView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" Title="WelcomeView" Height="450" Width="800"> <Grid> <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center" > <TextBlock Text="{Binding Welcome.Introduction}" FontSize="30" ></TextBlock> </StackPanel> </Grid> </Window>
TextBlock 綁定了 Welcome.Introduction,所以應該顯示Welcome對象下的Introduction屬性。
這時候的ViewModel和View是沒有任何關系的,所以我們在code-Behind的構造函數中寫上如下代碼:
using Pvd.ViewModel; using System.Windows; namespace Pvd.View { /// <summary> /// WelcomeView.xaml 的交互邏輯 /// </summary> public partial class WelcomeView : Window { public WelcomeView() { InitializeComponent(); this.DataContext = new WelcomeViewModel(); } } }
把 WelcomeViewModel 賦值給當前視圖的數據上下文。所以可以在當前視圖中使用ViewModel中所有的公開屬性和命令。
執行結果正常
總結:
1、通過 this.DataContext = new WelcomeViewModel(); 把 View 和 ViewModel 綁定。綁定后,可以直接在View中調用 ViewModel中公開的屬性和命令
2、所有的VideModel 都需要繼承於:ViewModelBase
3、所有的Model都繼承於ObservableObject
4、定義屬性方法如下,並在每個屬性中都加上RaisePropertyChanged(PropertyName)的調用,就可以實現對UI的交互更新了。
private String ~introduction;
public String Introduction
{
get { return ~introduction; }
set { ~introduction= value; RaisePropertyChanged(() => Introduction); }
}
新手入門,理解上有偏差,請各位老師提寶貴意見。