WPF快速搭建MVVM框架

WPFDemo项目结构:

需更改App.xaml上的属性StartupUri="Views/MainWindow.xaml"

Views:

MainWindow.xaml

<Window x:Class="WPFDemo.Views.MainWindow"
        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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPFDemo"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="3*"/>
            <ColumnDefinition Width="1*"/>
        </Grid.ColumnDefinitions>

        <DataGrid Margin="20" ItemsSource="{Binding data}" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="序号" Binding="{Binding Id}"/>
                <DataGridTextColumn Header="姓名" Width="150" Binding="{Binding Name}"/>
                <DataGridTextColumn Header="手机号" Width="150" Binding="{Binding Phone}"/>
                <DataGridTextColumn Header="省份" Binding="{Binding Province}"/>
            </DataGrid.Columns>
        </DataGrid>

        <Button Command="{Binding loadDataCommand}" Content="load data" 
                VerticalAlignment="Top" Margin="25" Grid.Column="1" Width="100" Height="50"/>
    </Grid>
</Window>

MainWindow.cs

namespace WPFDemo.Views
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainWindowViewModel();
        }
    }
}

ViewModels:

MainWindowViewModel.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using WPFDemo.Common;
using WPFDemo.Models;

namespace WPFDemo.ViewModels
{
    public class MainWindowViewModel
    {
        public ICommand loadDataCommand { get; set; }

        public ObservableCollection<Person> data { get; set; } = new ObservableCollection<Person>();
        
        public MainWindowViewModel()
        {
            loadDataCommand = new RelayCommand(loadData);
        }

        private void initData()
        {
            for(int i = 1; i <= 100; i++)
            {
                data.Add(new Person { Id = i, Name = "zhangsan" + i, Phone = "1000" + i, Province = "beijing" + i });
            }
        }

        private void loadData(object parameter)
        {
            initData();
        }


    }
}

Models:

Person.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WPFDemo.Models
{
    public class Person : INotifyPropertyChanged
    {
        #region properties

        private int _id;
        private string _name;
        private string _phone;
        private string _province;

        public int Id 
        {
            get { return _id; }
            set { _id = value; NotifyPropertyChanged(nameof(Id)); }
        }
        public string Name
        {
            get { return _name; }
            set { _name = value; NotifyPropertyChanged(nameof(Name)); }
        }
        public string Phone
        {
            get { return _phone; }
            set { _phone = value; NotifyPropertyChanged(nameof(Phone)); }
        }
        public string Province
        {
            get { return _province; }
            set { _province = value; NotifyPropertyChanged(nameof(Province)); }
        }

        #endregion properties

        #region Notify

        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged(string PropertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
        }

        #endregion Notify
    }
}

Common:

RelayCommand.cs

using System;
using System.Windows.Input;

namespace WPFDemo.Common
{
    public class RelayCommand : ICommand
    {
        private Func<object, bool> _canExecute;
        private Action<object> _execute;

        public RelayCommand(Action<object> execute) : this(null, execute)
        {
            _execute = execute;
        }

        public RelayCommand(Func<object, bool> canExecute, Action<object> execute)
        {
            this._canExecute = canExecute;
            this._execute = execute;
        }

        public event EventHandler CanExecuteChanged
        {
            add
            {
                if(_canExecute!=null)
                    CommandManager.RequerySuggested += value;
            }
            remove 
            {
                if(_canExecute!=null)
                    CommandManager.RequerySuggested -= value; 
            }
        }

        public bool CanExecute(object parameter)
        {
            return parameter != null ? _canExecute(parameter) : true;
        }

        public void Execute(object parameter)
        {
            _execute(parameter);
        }
    }
}

点击load data按钮方可加载数据,运行效果如下:

各位访客,如果运行不通,可添加以下qq群:获取最新源码及共同学习:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值