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("用户未找到");

}

相关推荐
九鼎科技-Leo10 小时前
什么是 WPF 中的依赖属性?有什么作用?
windows·c#·.net·wpf
麻花201320 小时前
C#之WPF的C1FlexGrid空间的行加载事件和列事件变更处理动态加载的枚举值
开发语言·c#·wpf
lcintj20 小时前
【WPF】Prism学习(九)
学习·wpf·prism
界面开发小八哥20 小时前
界面控件DevExpress WPF中文教程:网格视图数据布局的列和卡片字段
wpf·界面控件·devexpress·ui开发·用户界面
△曉風殘月〆20 小时前
如何在WPF中嵌入其它程序
wpf
Crazy Struggle21 小时前
功能齐全的 WPF 自定义控件资源库(收藏版)
.net·wpf·ui控件库
shepherd枸杞泡茶1 天前
WPF动画
c#·.net·wpf
lcintj1 天前
【WPF】Prism学习(十)
学习·wpf·prism
wyh要好好学习1 天前
WPF数据加载时添加进度条
ui·wpf
code_shenbing1 天前
跨平台WPF框架Avalonia教程 三
前端·microsoft·ui·c#·wpf·跨平台·界面设计