MVVM下DataGrid的简单应用

基于MVVM模式下DataGrid的简单应用,本实例将实现一个用户列表的展示和一些数据操作功能,如图1。

图1

实例要求:

(1)实现用户列表的绑定。

(2)绑定性别属性时,使用Converter对性别属性的转化。

(3)绑定日期时,对日期格式的转换。

(4)点击“编辑”按钮能够获取用户信息。

(5)点击“删除”按钮能够获取用户编号。

1、实体层

在实体层中创建用户信息实体类(UserModel.cs)。

/// <summary>
/// 用户信息实体类
/// </summary>
public class UserModel : INotifyPropertyChanged
{
    private int _id;
    /// <summary>
    /// 编号
    /// </summary>
    public int Id
    {
        get { return _id; }
        set
        {
            _id = value;
            this.NotifyPropertyChanged("Id");
        }
    }

    private string _name;
    /// <summary>
    /// 姓名
    /// </summary>
    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            this.NotifyPropertyChanged("Name");
        }
    }

    private int _sex;
    /// <summary>
    /// 性别(0:男,1:女)
    /// </summary>
    public int Sex
    {
        get { return _sex; }
        set
        {
            _sex = value;
            this.NotifyPropertyChanged("Sex");
        }
    }

    private DateTime? _jobDate;
    /// <summary>
    /// 入职时间
    /// </summary>
    public DateTime? JobDate
    {
        get { return _jobDate; }
        set
        {
            _jobDate = value;
            this.NotifyPropertyChanged("JobDate");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }  
}

2、ViewModel层

在ViewModel层中创建用户列表ViewModel类(UserListViewModel.cs)。

/// <summary>
/// 用户列表ViewModel类
/// </summary>
public class UserListViewModel : INotifyPropertyChanged
{
    public List<UserModel> _userList = new List<UserModel>();
    /// <summary>
    /// 用户列表
    /// </summary>
    public List<UserModel> UserList
    {
        get
        {
            return this._userList;
        }
        set
        {
            this._userList = value;
            this.RaisePropertyChanged("_userList");
        }
    }

    /// <summary>
    /// 初始化
    /// </summary>
    public UserListViewModel()
    {
        //加载数据
        UserList = new List<UserModel>(){
            new UserModel(){Id=1,Name="张三",Sex=0,JobDate=DateTime.Now},
            new UserModel(){Id=2,Name="李四",Sex=1,JobDate=DateTime.Now},
            new UserModel(){Id=3,Name="王五",Sex=0,JobDate=DateTime.Now},
            new UserModel(){Id=4,Name="孙六",Sex=0,JobDate=DateTime.Now},
            new UserModel(){Id=5,Name="黄七",Sex=1,JobDate=DateTime.Now},
        };
    }

    //属性改变事件
    public event PropertyChangedEventHandler PropertyChanged;

    //当属性改变的时候,调用该方法来发起一个消息,通知View中绑定了propertyName的元素做出调整
    public void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

/// <summary>
/// 编辑命令
/// </summary>
public class EditCommand : ICommand
{
    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        UserModel userInfo = parameter as UserModel;
        if(userInfo!=null)
        {
            //执行编辑
        }
    }
}

/// <summary>
/// 删除命令
/// </summary>
public class DeleteCommand : ICommand
{
    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        int id = (int)parameter;
        if (id > 0)
        {
            //执行删除
        }
    }
}

3、表现层

在表现层中创建Converter目录,并创建SexConverter.cs,用于对性别属性的转换。

public class SexConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string result = "";
        string sex = value.ToString();
        if (sex == "0")
        {
            result = "男";
        }
        else if (sex == "1")
        {
            result = "女";
        }
        return result;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

创建用户列表窗体(UserList.xaml)。

前台代码:

<Window x:Class="Simple.Calculator.WinForm.UserList"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:Simple.Calculator.ViewModel;assembly=Simple.Calculator.ViewModel"
        xmlns:conv="clr-namespace:Simple.Calculator.WinForm.Converter"
        Title="用户列表" Height="260" Width="400">
    <Window.Resources>
        <!--DataGrid样式-->
        <Style TargetType="{x:Type DataGrid}" x:Key="gDataGrid">
            <Setter Property="Margin" Value="0,10,0,10"/>
            <Setter Property="HorizontalGridLinesBrush" Value="#c5cfd8"/>
            <Setter Property="VerticalGridLinesBrush" Value="#c5cfd8"/>
            <Setter Property="AutoGenerateColumns" Value="False"/>
            <Setter Property="CanUserSortColumns" Value="False"/>
            <Setter Property="IsReadOnly" Value="True"/>
        </Style>
        <Style TargetType="DataGridRow">
            <Setter Property="Height" Value="32"/>
            <Setter Property="FontSize" Value="12" />
        </Style>
        <Style TargetType="DataGridColumnHeader">
            <Setter Property="SnapsToDevicePixels" Value="True" />
            <Setter Property="MinWidth" Value="0" />
            <Setter Property="MinHeight" Value="32" />
            <Setter Property="Foreground" Value="#667a95" />
            <Setter Property="FontSize" Value="14" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="DataGridColumnHeader">
                        <Border x:Name="BackgroundBorder" BorderThickness="0,1,0,1" 
                             BorderBrush="#e6dbba" 
                              Width="Auto">
                            <Grid >
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="*" />
                                </Grid.ColumnDefinitions>
                                <ContentPresenter  Margin="0,0,0,0" VerticalAlignment="Center" HorizontalAlignment="Center"/>
                                <Path x:Name="SortArrow" Visibility="Collapsed" Data="M0,0 L1,0 0.5,1 z" Stretch="Fill"  Grid.Column="2" Width="8" Height="6" Fill="White" Margin="0,0,50,0" 
                            VerticalAlignment="Center" RenderTransformOrigin="1,1" />
                                <Rectangle Width="1" Fill="#c5cfd8" HorizontalAlignment="Right" Grid.ColumnSpan="1" />
                            </Grid>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Setter Property="Height" Value="30"/>
        </Style>

        <!--命令-->
        <vm:EditCommand x:Key="EditCommand"/>
        <vm:DeleteCommand x:Key="DeleteCommand"/>

        <!--Converter-->
        <conv:SexConverter x:Key="SexConverter"/>
    </Window.Resources>
    
    <!--列表-->
    <DataGrid Grid.Row="1" Margin="10" Style="{StaticResource gDataGrid}" ItemsSource="{Binding UserList, Mode=TwoWay}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="姓名" Width="90" Binding="{Binding Name}"/>
            <DataGridTextColumn Header="性别" Width="90" Binding="{Binding Sex,Converter={StaticResource SexConverter}}"/>
            <DataGridTextColumn Header="入职时间" Width="*" Binding="{Binding JobDate,StringFormat=yyyy-MM-dd}"/>
            <DataGridTemplateColumn Header="操作" Width="90">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <Button Content="详情" Margin="10,0" Command="{StaticResource EditCommand}" CommandParameter="{Binding}" />
                            <Button Content="删除" Command="{StaticResource DeleteCommand}" CommandParameter="{Binding Id}" />
                        </StackPanel>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
</Window>

后台代码:

/// <summary>
/// UserList.xaml 的交互逻辑
/// </summary>
public partial class UserList : Window
{
    public UserList()
    {
        InitializeComponent();
        this.DataContext = new UserListViewModel();
    }
}

 

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

pan_junbiao

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

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

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

打赏作者

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

抵扣说明:

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

余额充值