WPF使用DataGrid显示数据的小例子(重点是使用了MVC模式)

程序运行结果如下:
在这里插入图片描述
首先,新建一个wpf项目,取名TestDataGrid
在MainWindow.xmal中添加如下代码:

<Window x:Class="TestDataGrid.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:TestDataGrid"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="283*"/>
            <RowDefinition Height="38*"/>
        </Grid.RowDefinitions>
        <DataGrid AutoGenerateColumns="False" x:Name="dataGrid" Grid.Row="0" IsReadOnly="True" MinWidth="30" CanUserSortColumns="True" ItemsSource="{Binding mainEneitiesFilter}" CanUserAddRows="False">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding nID}" Header="序号"/>
                <DataGridTextColumn Binding="{Binding sName}" Header="姓名"/>
                <DataGridTextColumn Binding="{Binding sSex}" Header="性别"/>
                <DataGridTemplateColumn IsReadOnly="True" MinWidth="20" CanUserReorder="True">
                    <DataGridTemplateColumn.Header>
                        <TextBlock Cursor="Hand" Text="是否录用"/>
                    </DataGridTemplateColumn.Header>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox IsEnabled="True" IsChecked="{Binding bUse}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
        <UniformGrid Grid.Row="2" Rows="1">
            <CheckBox x:Name="checkBox" Content="全选" HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Row="1" IsChecked="{Binding isAllCheck}" Command="{Binding SelectAllCommand}"/>
        </UniformGrid>
    </Grid>
</Window>

MainWindow.xaml.cs文件代码如下:

using System.Windows;

namespace TestDataGrid
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        mainViewModel mViewModel;
        public MainWindow()
        {
            InitializeComponent();
            mViewModel = new mainViewModel();
            DataContext = mViewModel;

        }
    }
}

mainViewModel.cs文件代码如下:

using System.Collections.ObjectModel;//为了使用ObservableCollection<>
using System.ComponentModel;//为了继承INotifyPropertyChanged接口类
using System.Windows.Input;

namespace TestDataGrid
{
    class mainViewModel : INotifyPropertyChanged
    {
        public mainViewModel()
        {
            _isAllCheck = false;
            mainEneitiesFilter = new ObservableCollection<mainViewEntitie>();
            for(int i = 0;i<5;i++)
            {
                mainViewEntitie viewEntity = new mainViewEntitie();
                viewEntity.nID = i + 1;
                viewEntity.sName = "name" + i.ToString();
                if(0 == i%2)
                {
                    viewEntity.sSex = "male";
                }
                else
                {
                    viewEntity.sSex = "female";
                }                
                viewEntity.bUse = false;
                mainEneitiesFilter.Add(viewEntity);
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        private ObservableCollection<mainViewEntitie> _mainEntitiesFilter;
        public ObservableCollection<mainViewEntitie> mainEneitiesFilter
        {
            get
            {
                return _mainEntitiesFilter;
            }
            set
            {
                _mainEntitiesFilter = value;                
            }
        }
        private bool _isAllCheck;
        public bool isAllCheck
        {
            get
            {
                return _isAllCheck;
            }
            set
            {
                _isAllCheck = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("isAllCheck"));
            }
        }
        public ICommand SelectAllCommand { get { return new CommandBase(SeletcAll); } }
        private void SeletcAll()
        {
            for(int i = 0;i<mainEneitiesFilter.Count;i++)
            {
                if(_isAllCheck)
                {
                    mainEneitiesFilter[i].bUse = true;
                }
                else
                {
                    mainEneitiesFilter[i].bUse = false;
                }
                
            }
        }
    }
}

mainViewEntitie.cs文件代码如下:

using System.ComponentModel;

namespace TestDataGrid
{
    class mainViewEntitie : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private string _sName;
        public string sName
        {
            get
            {
                return _sName;
            }
            set
            {
                _sName = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("sName"));
                }
                    
            }
        }
        private string _sSex;
        public string sSex
        {
            get
            {
                return _sSex;
            }
            set
            {
                _sSex = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("sSex"));
                }
            }
        }
        private int _nID;
        public int nID
        {
            get
            {
                return _nID;
            }
            set
            {
                _nID = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("nID"));
                }
            }
        }
        private bool _bUse;
        public bool bUse
        {
            get
            {
                return _bUse;
            }
            set
            {
                _bUse = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("bUse"));
                }
            }
        }
    }
}

CommandBase.cs文件代码如下:

using System;
using System.Windows.Input;

namespace TestDataGrid
{
    internal class CommandBase : ICommand
    {
        private readonly Action<object> _commandpara;
        private readonly Action _command;
        private readonly Func<bool> _canExecute;

        public CommandBase(Action command, Func<bool> canExecute = null)
        {
            if (command == null)
            {
                throw new ArgumentNullException();
            }
            _canExecute = canExecute;
            _command = command;
        }

        public CommandBase(Action<object> commandpara, Func<bool> canExecute = null)
        {
            if (commandpara == null)
            {
                throw new ArgumentNullException();
            }
            _canExecute = canExecute;
            _commandpara = commandpara;
        }

        public bool CanExecute(object parameter)
        {
            return _canExecute == null || _canExecute();
        }
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public void Execute(object parameter)
        {
            if (parameter != null)
            {
                _commandpara(parameter);
            }
            else
            {
                if (_command != null)
                {
                    _command();
                }
                else if (_commandpara != null)
                {
                    _commandpara(null);
                }
            }
        }

        public bool Execute2(object parameter)
        {
            if (parameter != null)
            {
                _commandpara(parameter);
                return true;
            }
            else
            {
                if (_command != null)
                {
                    _command();
                    return true;
                }
                else if (_commandpara != null)
                {
                    _commandpara(null);
                    return true;
                }
                return true;
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GreenHandBruce

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值