天天看點

MVVM下DataGrid的簡單應用

基于MVVM模式下DataGrid的簡單應用,本執行個體将實作一個使用者清單的展示和一些資料操作功能,如圖1。

MVVM下DataGrid的簡單應用

圖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();
    }
}
           

繼續閱讀