WPF在MVVM架构下使用DataGrid并实现行删除

一、效果演示

二、Model创建

cs 复制代码
    //User:用于绑定DataGrid控件的数据 
    private ObservableCollection<User> _users = new ObservableCollection<User>();
    public ObservableCollection<User> Users
    {
        get { return _users; }
        set { _users = value; }
    }

    //SelectedUser:用于存放DataGrid当行选中时的数据
    private User _selectedUser;
    public User SelectedUser
    {
        get { return _selectedUser; }
        set
        {
            _selectedUser = value;
            OnPropertyChanged(nameof(SelectedUser));
        }
    }

}

//自定义数据结构
public class User
{
    public int Id { get; set; }

    public string Name { get; set; }

    public DateTime Birthday { get; set; }
    public int Sex { get; set; }

    public string School { get; set; }
}

ObservableCollection<T> 是一个特殊的集合类,它继承自 INotifyCollectionChangedINotifyPropertyChanged 接口

ObservableCollection<T> 中的项目被添加、删除或替换时,它会触发 CollectionChanged 事件。这个事件可以被绑定的UI元素(如DataGrid, ListView等)捕获,从而自动更新其显示的内容

三、ViewModel创建

为DataGrid添加数据

cs 复制代码
 public Page2ViewModel() 
 {
//为Users添加数据
     for(int i = 0; i < 20; i=i+5)
     {
         Page2Model.Users.Add(new User() { Id = i, Name = "A Doe", Birthday = new DateTime(1971, 7, 23), Sex = 1, School = "A" });
         Page2Model.Users.Add(new User() { Id = i+1, Name = "B Doe", Birthday = new DateTime(1974, 1, 17), Sex = 0, School = "B" });
         Page2Model.Users.Add(new User() { Id = i+2, Name = "C Doe", Birthday = new DateTime(1991, 9, 2), Sex = 1, School = "C" });
         Page2Model.Users.Add(new User() { Id = i+3, Name = "D Doe", Birthday = new DateTime(1971, 7, 23), Sex = 1, School = "A" });
         Page2Model.Users.Add(new User() { Id = i+4, Name = "E Doe", Birthday = new DateTime(1974, 1, 17), Sex = 0, School = "B" });
     }
     
 }

按钮操作

cs 复制代码
public CommandBase DataAddition
{
    get => new CommandBase
    {
        DoExecte = new Action<object>(CalcDataAddition)
    };
}
private void CalcDataAddition(object obj)
{
    Page2Model.Users.Add(new User() { Id = 3, Name = "***", Birthday = new DateTime(1991, 9, 2), Sex = 1, School = "C" });

}


public CommandBase DataDeletion
{
    get => new CommandBase
    {
        DoExecte = new Action<object>(CalcDataDeletion)
    };
}
private void CalcDataDeletion(object obj)
{
    Debug.WriteLine("用户删除按钮按下");
    User userToRemove = Page2Model.Users.FirstOrDefault(u => u.Id == 1); // 假设你根据Id查找用户  
    if (userToRemove != null)
    {
        Page2Model.Users.Remove(userToRemove);
    }
    else
    {
        Debug.WriteLine("用户未找到");
    }
}

public CommandBase IdQuery
{
    get => new CommandBase
    {
        DoExecte = new Action<object>(CalcIdQuery)
    };
}
private void CalcIdQuery(object obj)
{
    //Debug.WriteLine($"Selected User: {Page2Model.SelectedUser.Id}");
    User userToRemove = Page2Model.Users.FirstOrDefault(u => u.Id == Page2Model.SelectedUser.Id); // 假设你根据Id查找用户  
    if (userToRemove != null)
    {
        Page2Model.Users.Remove(userToRemove);
    }
    else
    {
        Debug.WriteLine("用户未找到");
    }
}

四、VIew

html 复制代码
 <Grid Background="White">
     <Grid.RowDefinitions>
         <RowDefinition Height="3*" />
         <RowDefinition Height="1*" />
     </Grid.RowDefinitions>
     <DataGrid x:Name="dgSimple" AutoGenerateColumns="False"  VerticalAlignment="Top"
                               CanUserSortColumns="False"     Margin="5" IsReadOnly="True"
                               CanUserResizeColumns="False" CanUserResizeRows="False"  SelectionMode="Single"
                               CanUserReorderColumns="False" AlternationCount="2"  RowHeaderWidth="0" CanUserAddRows="False" ItemsSource="{Binding Page2Model.Users}"  SelectedItem="{Binding Page2Model.SelectedUser, Mode=TwoWay}" >
         <DataGrid.Columns>
             <DataGridTextColumn Header="序号" Width="150"  Binding="{Binding  Id}"/>
             <DataGridTextColumn Header="姓名"   Width="120"  Binding="{Binding Name}"/>
             <DataGridTextColumn Header="生日"  Width="120"  Binding="{Binding Birthday}"/>
             <DataGridTextColumn Header="性别"  Width="130"  Binding="{Binding Sex}"/>
             <DataGridTextColumn Header="学校"  Width="140"  Binding="{Binding School}"/>
             <DataGridTemplateColumn  Header="操作"  Width="140" >
                 <DataGridTemplateColumn.CellTemplate>
                     <DataTemplate>
                         <StackPanel Orientation="Horizontal">
                             <Button  Content="删除" Height="34"  Command="{Binding DataContext.IdQuery , RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"  
                                 CommandParameter="{Binding}" Width="80" FontSize="20"    HorizontalAlignment="Center" VerticalAlignment="Center">
                             </Button>
                         </StackPanel>
                     </DataTemplate>
                 </DataGridTemplateColumn.CellTemplate>
             </DataGridTemplateColumn>
         </DataGrid.Columns>
     </DataGrid>

     <Grid Grid.Row="1" >
         <StackPanel Orientation="Horizontal" >
             <Button  Content="数据添加" Width="150" Height="40" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10 15 0 0" Command="{Binding DataAddition}"/>
             <Button  Content="数据删除" Width="150" Height="40" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10 15 0 0" Command="{Binding DataDeletion}"/>
             <Button  Content="ID查询" Width="150" Height="40" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10 15 0 0" Command="{Binding IdQuery}"/>
         </StackPanel>
         
     </Grid>
     
     
     
 </Grid>

实现按钮按下就删除行的重点为

SelectedItem="{Binding Page2Model.SelectedUser, Mode=TwoWay}"

当选中行时SelectedUser变量就会更新为选中的行的内容,

User userToRemove = Page2Model.Users.FirstOrDefault(u => u.Id == Page2Model.SelectedUser.Id); //当ID对上时将会删除

if (userToRemove != null)

{

Page2Model.Users.Remove(userToRemove);

}

else

{

Debug.WriteLine("用户未找到");

}

相关推荐
就是有点傻2 小时前
WPF中ImageBrush和Image的区别
wpf
冷眼Σ(-᷅_-᷄๑)2 小时前
WPF如何使用外部字体
wpf
月落.1 天前
WPF的<ContentControl>控件
wpf
就是有点傻1 天前
WPF中的依赖属性
开发语言·wpf
wangnaisheng1 天前
【WPF】把一个Window放在左上角/右上角顶格显示
wpf
WineMonk1 天前
.NET WPF CommunityToolkit.Mvvm框架
.net·wpf·mvvm
月落.1 天前
WPF中的INotifyPropertyChanged接口
wpf
界面开发小八哥1 天前
界面控件DevExpress WPF中文教程:Data Grid——卡片视图设置
.net·wpf·界面控件·devexpress·ui开发
平凡シンプル1 天前
WPF 打包
wpf
VickyJames1 天前
基于XAML框架和跨平台项目架构设计的深入技术分析
wpf·开源分享·unoplatform·winui3·项目架构