0
点赞
收藏
分享

微信扫一扫

简单WPF MVVM实现

NicoalsNC 2022-02-23 阅读 92

引用库

  1. Addin.Light;
  2. Addin.Wpf;
  3. System.Windows.Interactivity.dll

创建项目
创建文件
MainView.xaml;
MainViewModel.cs;

编写代码
MainViewModel代码如下:


using Addin.Wpf.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace EmitMvvm
{
    [MVVM]
    public class MainViewModel
    {
        [MVVMView]
        private MainView view;

        [MVVM]
        public virtual int Age { get; set; }
        [MVVM]
        public virtual String Name { get; set; }

        [MVVMCommand]
        public void ShowAge(MVVMEventArg arg) => this.Age = 12;

        [MVVMCommand("Hello")]
        public void ShowName() => this.Name = "张三";

        [MVVMCommand]
        public void ViewLoaded(MVVMEventArg arg) => view.Title = "你好";
    }
}

MainView代码如下:

<Window
    x:Class="EmitMvvm.MainView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="clr-namespace:EmitMvvm"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:mvvm="clr-namespace:Addin.Wpf.Mvvm;assembly=Addin.Wpf"
    Title="MainWindow"
    Width="800"
    Height="450"
    d:DataContext="{d:DesignInstance Type=local:MainViewModel}"
    mvvm:ViewModelFilter.CommandName="Loaded@ViewLoaded"
    mvvm:ViewModelFilter.ViewModel="{x:Type local:MainViewModel}"
    mc:Ignorable="d">
    <Grid>

        <StackPanel>
            <TextBox Text="{Binding Name}" />
            <TextBox Text="{Binding Age}" />
            <Button mvvm:ViewModelFilter.CommandName="Click@Hello" Content="点击一下(无参数)" />
            <Button
                mvvm:ViewModelFilter.CommandName="Click@ShowAge"
                mvvm:ViewModelFilter.CommandParameter="{Binding Name}"
                Content="点击一下(有参数)" />
        </StackPanel>
    </Grid>
</Window>

ICommand的使用,可以使用传统方式,示例


public ICommand ViewLoadCommand
{
    get
    {
        retrun RelayCommand.Create(()=>{...});
    }
}

等文件审核通过后,我将在评论区上传相关文件

举报

相关推荐

0 条评论