之前的blog中讲了很多比较细化的知识点,但是在开发过程中如何保持一个比较好的开发模式是前期开发中比较困惑的地方。这里就讲解下MVVM开发模式,也是目前WPF开发中普遍采用的开发模式。
MVVM 模式就是 View ViewModel Model :将前后端开发分离,保持了较好的低耦合,便于后期的维护,也比较好的表现了数据驱动的运行模式。
我在自己的开发过程中总结了MVVM模式开发要遵循的几个要求
1:在xaml的后置文件cs中不编写业务代码。
2:xmal中是数据都通过Binding来进行UI渲染。
3:ViewModel 中编写业务处理的代码,并且不能有操作对view直接操作的代码。
4:控件的命令和事件,属性也要通过binding的模式来进行编写。
遵循上面几个要求就能编写出简洁高效的代码并从中体会到数据驱动的美妙之处,但是MVVM并没有严格的限制,具体的开发实现还要根据具体的业务需求来进行调整。
下面就分三个部分View ViewModel Model来进行讲解。
View:
<UserControl
x:Class="AlphaLog.UserControls.UserDelPanel"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Metro="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:interactivity="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:AlphaLog.UserControls"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Width="250"
Height="150">
<!-- 事件的绑定 -->
<interactivity:Interaction.Triggers>
<interactivity:EventTrigger EventName="Loaded">
<interactivity:InvokeCommandAction Command="{Binding LoadedCommand}" />
</interactivity:EventTrigger>
</interactivity:Interaction.Triggers>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="60" />
</Grid.RowDefinitions>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock
Grid.Row="0"
Grid.Column="0"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Text="User:" />
<TextBox
x:Name="txtUserName"
Grid.Row="0"
Grid.Column="1"
Width="130"
Height="25"
HorizontalAlignment="Left"