WPF MVVM Prism

  1. View负责前端展示,与ViewModel进行数据和命令的交互。
  2. ViewModel,负责前端视图业务级别的逻辑结构组织,并将其反馈给前端。
  3. Model,主要负责数据实体的结构处理,与ViewModel进行交互。

命令创建方式

方式一:

public DelegateCommand GetTextCommnd { get; set; }
public MainWindowViewModel()
{
    this.GetTextCommnd = new DelegateCommand(new Action(ExecuteGetTextCommnd));
}
void ExecuteGetTextCommnd()
{
    System.Windows.MessageBox.Show(Obj.Text);
}

方式二:

public DelegateCommand<Button> LoginCommand
{
    get
    {
        return new DelegateCommand<Button>((p) =>
        {
                    
        });
    }
}

方式三:

private DelegateCommand _getTextCommnd;
public DelegateCommand GetTextCommnd => _getTextCommnd ?? (_getTextCommnd = new DelegateCommand(ExecuteGetTextCommnd));

void ExecuteGetTextCommnd()
{
    System.Windows.MessageBox.Show(Obj.Text);
}

  


 

项目结构:

WPF MVVM Prism

 

 

Model 类

using Prism.Mvvm;

namespace WpfPrism.Models
{
    public class MainWindowModel : BindableBase
    {
        private string _text;
        public string Text
        {
            get { return _text; }
            set { SetProperty(ref _text, value); }
        }
    }
}

  

ViewModel 类

using System;
using Prism.Commands;
using Prism.Mvvm;
using WpfPrism.Models;

namespace WpfPrism.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        public MainWindowViewModel()
        {
            Obj = new MainWindowModel();
            Obj.Text = "默认值";
        }
        public MainWindowModel Obj { set; get; }

        private DelegateCommand _setTextCommnd;
        public DelegateCommand SetTextCommnd =>
            _setTextCommnd ?? (_setTextCommnd = new DelegateCommand(ExecuteSetTextCommnd));

        void ExecuteSetTextCommnd()
        {
            Obj.Text = "已赋新值";
        }

        private DelegateCommand _getTextCommnd;
        public DelegateCommand GetTextCommnd =>
            _getTextCommnd ?? (_getTextCommnd = new DelegateCommand(ExecuteGetTextCommnd));

        void ExecuteGetTextCommnd()
        {
            System.Windows.MessageBox.Show(Obj.Text);
        }
    }
}

前端 XAML

<Grid>
    <StackPanel>
        <TextBox Text="{Binding Obj.Text}" Margin="10" Height="100" FontSize="50"/>
        <Button  Height="100" Width="300" Content="赋值" FontSize="50" Command="{Binding SetTextCommnd}" Margin="10"/>
        <Button  Height="100" Width="300" Content="取值" FontSize="50" Command="{Binding GetTextCommnd}"/>
    </StackPanel>
</Grid>

后台 CS

public MainWindow()
{
    InitializeComponent();
    DataContext = new MainWindowViewModel();
}

  

WPF MVVM Prism

 

WPF MVVM Prism

上一篇:深入理解WPF路由事件


下一篇:都是俺自己的原创。日记。搞笑考古资料。蓝咪咪日记。