WPF中使用DataGrid时操作列按钮问题


在使用DataGrid的过程中,我们有时候需要对选取的某一行数据进行多个操作,这个时候操作列只有一个按钮显然无法满足我们的要求,我们需要多个按钮才能达到我们的目的。

UI页面代码:

    
        
            
                
            

            
                
                
                
                
                
                    
                        
                            
                                
                                
                            
                        
                    
                
            
        
    

 后台代码:

        List users = new List();
        //向DataGrid中添加数据
        private void GetDataGrid()
        {
            for (int i = 0; i < 10; i++)
            {
                User user = new User();
                user.Name = "Tom"; user.Sex = "男"; user.Age = "18"; user.Phone = "000000";
                user.BtnActionStr = "按钮" + i;
                user.BtnActionStr1 = "按钮" + (i + 1);
                if (i % 2 == 0)
                {
                    user.Enabled = true;
                    user.Enabled1 = false;
                }
                else
                {
                    user.Enabled = false;
                    user.Enabled1 = true;
                }
                users.Add(user);
            }
            //数据绑定
            datagrid.ItemsSource = users;
        }
        //定义要绑定的类
        private class User
        {
            public string Name { get; set; }
            public string Sex { get; set; }
            public string Age { get; set; }
            public string Phone { get; set; }
            public string BtnActionStr { get; set; }
            public bool Enabled { get; set; }
            public string BtnActionStr1 { get; set; }
            public bool Enabled1 { get; set; }
        }
        //平均分配各列的宽度
        private void datagrid_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            int WidthSize = (int)(datagrid.ActualWidth / 5 - 4);
            UserName.Width = WidthSize; UserSex.Width = WidthSize; UserAge.Width = WidthSize;
            UserPhone.Width = WidthSize; UserAction.Width = WidthSize;
        }
        //第一个按钮点击事件
        private void BtnAction_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(users[datagrid.SelectedIndex].Name);
        }
        //第二个按钮点击事件
        private void BtnAction1_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(users[datagrid.SelectedIndex].Sex);
        }

 调用:

GetDataGrid();

 效果图: