你的位置:首页 > ASP.net教程

[ASP.net教程]MVVM初步搭建应用


MVVM模式:
利用 prism Microsoft.Practices.Prism.dll
WPF Interaction框架简介 添加Interactions库的引用。主要添加如下两个DLL:
Microsoft.Expression.Interactions.dll和System.Windows.Interactivity.dll(一般系统自带),像Load时候的command
要先引用

调用方式:

<i:Interaction.Triggers>    <i:EventTrigger>      <i:InvokeCommandAction Command="{Binding LoadCommand}" />    </i:EventTrigger>  </i:Interaction.Triggers>

<!--ComboBox绑定下拉列表--><ComboBox x:Name="cbYear" ItemsSource="{Binding Path=YearList,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Path=SelectedYear}">            <i:Interaction.Triggers>              <i:EventTrigger EventName="SelectionChanged" SourceObject="{Binding ElementName=cbYear}">                <i:InvokeCommandAction Command="{Binding YearChangedCommand}" CommandName="YearChangedCommand"/>              </i:EventTrigger>            </i:Interaction.Triggers>          </ComboBox>

绑定按钮用  Command 如Command="{Binding LoginCommand}"

在设计界面:<Button Content="登录" Name="btn_Login" Command="{Binding LoginCommand}"></Button>

在cs也可以写:

this.btn_Login.Click += new RoutedEventHandler(btn_Login_Click);MainWindowViewModel viewModel = new MainWindowViewModel();void btn_Login_Click(object sender, RoutedEventArgs e){viewModel.LoginCommand.Execute();}

接下来就要写view对应的ViewModel了 MainWindowViewModel,如果需要绑定界面值,如textbox文本框,能够动态显示值
,这个需要用到Prism,类需要集成NotificationObject

public class MainWindowViewModel : NotificationObject  {    private string _userName= string.Empty;    public string UserName    {      get { return _userName; }      set      {        _userName = value;        RaisePropertyChanged("UserName");      }    }  //定义Command    public DelegateCommand LoadCommnad { get; set; } public MainWindowViewModel()    {      this.LoginCommand = new DelegateCommand(Login);//Command调用Login方法    }//响应Command private void Login()    {      if (string.IsNullOrEmpty(UserName))      {        UserName = "用户名为空";//前台文本框会显示      }    }}