MVVM模式初学

MVVM模式,在我看来,这就是一个MVC的模式。

WPF界面很精美,但是控制的控制却不是很容易,MVVM我感觉,非常好的解决了这个难题。View就是界面,就是负责显示内容的。依靠binding界面的数据操作以及改变都可以单独拿出来,放到后台去控制。当然这也只是我的简单的理解。

Model:数据层(同MVC中的Model)

View:界面层(同MVC中的View)

ViewModel:界面与数据的中间处理层(同MVC中的Control)

这样就好理解了吧。

下面举一个例子。

例子很简单,达到的效果就是前台页面上一个TextBlock控件,三个按钮,点一个按钮TB控件的背景颜色与内容改变。

View中的Xaml文件。TextBlock控件的属性为:

1
<TextBlock Height="129" HorizontalAlignment="Left" Background="{Binding BackColor,Mode=OneWay}" Margin="12,12,0,0" Name="Tb" Text="{Binding Name,Mode=OneWay}" VerticalAlignment="Top" Width="287"/>

主要的就是="{Binding BackColor,Mode=OneWay}"和="{Binding Name,Mode=OneWay}这两个绑定,和Model。

Model中写一个数据的类

 

1
2
3
4
public class TempProperty
    {
        public int count { set; get; }
    }

 

这样就可以了,count作为一个基础数据而已。

ViewModel中建立一个类,这个类继承INotifyPropertyChanged,就是为了后台的数据源更新,则前他的绑定的数据同时更新。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class CountViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private int _count;
        public int Name
        {
            get
            {
                return _count;
            }
            set
            {
                _count = value;
 
                if (value == 1) BackColor = "Red";
                if (value == 2) BackColor = "Blue";
                if (value == 3) BackColor = "Green";
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("Name"));
            }
        }
        private string _color;
        public string BackColor
        {
            get
            {
                return _color;
            }
            set
            {
                _color = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("BackColor"));
            }
        }
    }

View中进行初始化

1
2
3
4
5
6
7
private CountViewModel _countViewModel;
        public MainWindow()
        {
            InitializeComponent();
            _countViewModel = new CountViewModel();
            Tb.DataContext = _countViewModel;
        }

再进行按钮事件操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
private void button1_Click(object sender, RoutedEventArgs e)
        {
            this._countViewModel.Name = 1;
        }
 
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            this._countViewModel.Name = 2;
        }
 
        private void button3_Click(object sender, RoutedEventArgs e)
        {
            this._countViewModel.Name = 3;
        }

这样就可以了。当我们点击按钮的时候,就实现了前面所说的效果。

原文地址:https://www.cnblogs.com/Tally/p/2886377.html