在开发软件过程中有一些客户要求要在表个里面添加一列“状态列”在这列里面添加有按钮,这些按钮有“删除、编辑、停用、启用、修改、详细内容等等”。开发人员为了瞒足看客户的需求从而开发表格里面添加按钮的需求,每一行的按钮只能对他所在的一行进行操作,不能操作别的行的内容。

下面的的代码是WPF XAML的表格里面添加按钮的XAML的代码:

<Window x:Class="WpfApp1.Window3"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:core="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<ObjectDataProvider x:Key="SexEnumKey" MethodName="GetValues" ObjectType="{x:Type core:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type Type="local:SexEnum"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<Grid >
<DataGrid Name="userList" ItemsSource="{Binding}" AutoGenerateColumns="False" CanUserAddRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="编号" Width="80*" Binding="{Binding }" />
<DataGridTextColumn Header="客户名称" Width="80*" Binding="{Binding }" />
<DataGridComboBoxColumn Header="性别" Width="50*" SelectedItemBinding="{Binding sex}"
ItemsSource="{Binding Source={StaticResource SexEnumKey}}" />
<DataGridTextColumn Header="手机号" Width="80*" Binding="{Binding created_at}" />
<DataGridTemplateColumn Header="操作状态" Width="80*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
<Button Content="编辑" Name="Bianji" Tag="{Binding}" Click="Bianji_Click" />
<Button Content="删除" Name="Shangchu" Tag="{Binding}" Click="Shangchu_Click" Foreground="#FFE01919" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>

</Window>



C#的代码如下

行里面有按钮了然后对里面的按钮添加Click事件转到代码编写按钮对应的事件即可

        //编辑
private void Bianji_Click(object sender, RoutedEventArgs e)
{

}
//删除
private void Shangchu_Click(object sender, RoutedEventArgs e)
{

}



下图运行的码的效果截图

WPF DataGridTemplateColumn添加按钮和按钮事件获取行参数_ide

以上是本人参考了一些网上的资料做出的一个案例,如有不足的地方请指出、我会思考问题修改不足的地方。


注意:

这里建议按钮的绑定使用  ​ ​<Button Content="编辑" Name="Bianji" Tag="{Binding}" Click="Bianji_Click" />​

这样就可以在对应的Click事件中获取到当前行的Model对象,另外,还可以使用下面的方式获取绑定的数据

==========================================================================================



// 删除
private void BtnDelete_Click(object sender, RoutedEventArgs e)
{
//获取需要删除的行
//DataRowView SelectedRow = dgrdView.SelectedItem as DataRowView; //当你的DataGrid的ItemsSource是DataTable时使用该方式
var SelectedRow = (DemoViewModel)dgrdView.SelectedItem; //当你的DataGrid的ItemsSource是对象集合时使用该方式(这里我用的这个,我的对象集合是List<DemoViewModel>)

//其他逻辑代码,本处省略。。。

}


========================================================================

WPF 元素tag属性绑定一个属性或一个对象

直接上代码吧!



<Window x:Class="CollectionBinding.CategoryDataTemp"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="CategoryDataTemp" Height="300" Width="300">
<Grid>
<ListBox Margin="3" Name="lstCategories" HorizontalContentAlignment="Stretch">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Margin="3">
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock VerticalAlignment="Center" Text="{Binding Path=CategoryName}"></TextBlock>
<!--<Button Grid.Column="1" Padding="3" Click="View_Clicked" Tag="{Binding Path=CategoryID}">View...</Button>-->
<Button Grid.Column="1" Padding="3" Click="View_Clicked" Tag="{Binding}">View...</Button>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>



using ClassLibrary;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;


namespace CollectionBinding
{
/// <summary>
/// Interaction logic for CategoryDataTemp.xaml
/// </summary>
public partial class CategoryDataTemp : Window
{
public CategoryDataTemp()
{
InitializeComponent();
lstCategories.ItemsSource = StoreDB.GetProductsAndCategories().Tables["Categories"].DefaultView;
}


private void View_Clicked(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
//int categoryID = (int)btn.Tag; //绑定到CategoryID,例如Tag="{Binding CategoryID}" 或者 Tag="{Binding Path=CategoryID}"
//MessageBox.Show(categoryID.ToString());
DataRowView row = (DataRowView)btn.Tag;
MessageBox.Show(row["CategoryID"].ToString() + " : " + row["CategoryName"].ToString());
}
}

}

//数据库操作类
namespace ClassLibrary
{
public class StoreDB
{
public static string connString = Properties.Settings.Default.ConnectionString;

public static Product GetProductByID(int id)
{
Product p = null;
SqlConnection con = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("GetProductByID", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ProductID", id);
try
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
p = new Product()
{
CategoryID = (int)reader[1],
ModelNumber = reader[2].ToString(),
ModelName = reader[3].ToString(),
ProductImage=reader[4].ToString(),
UnitCost = (decimal)reader[5],
Description = reader[6].ToString()
};
}
return p;
}
catch (Exception)
{
throw;
}
finally
{
con.Close();
}
}


public static void UpdateProductByID(int ProductID,Product p)
{
SqlConnection con = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("UpdateProductByID", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ProductID",ProductID);
cmd.Parameters.AddWithValue("@CategoryID",p.CategoryID);
cmd.Parameters.AddWithValue("@ModelNumber",p.ModelNumber);
cmd.Parameters.AddWithValue("@ModelName",p.ModelName);
cmd.Parameters.AddWithValue("@ProductImage",p.ProductImage);
cmd.Parameters.AddWithValue("@UnitCost",p.UnitCost);
cmd.Parameters.AddWithValue("@Description",p.Description);
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
con.Close();
}
}

public static void InsertProduct(Product p)
{
SqlConnection con = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("InsertProduct", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CategoryID", p.CategoryID);
cmd.Parameters.AddWithValue("@ModelNumber", p.ModelNumber);
cmd.Parameters.AddWithValue("@ModelName", p.ModelName);
cmd.Parameters.AddWithValue("@ProductImage", p.ProductImage);
cmd.Parameters.AddWithValue("@UnitCost", p.UnitCost);
cmd.Parameters.AddWithValue("@Description", p.Description);
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
con.Close();
}
}


public static void DeleteProductByID(int id)
{
SqlConnection con = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("DeleteProductByID", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ProductID", id);
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
con.Close();
}
}

public static ObservableCollection<Product> GetProducts()
{
ObservableCollection<Product> products = new ObservableCollection<Product>();
SqlConnection con = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("GetProducts", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
try
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
products.Add(new Product()
{
ProductID = (int)reader[0],
CategoryID = (int)reader[1],
ModelNumber = reader[2].ToString(),
ModelName = reader[3].ToString(),
ProductImage = reader[4].ToString(),
UnitCost = (decimal)reader[5],
Description = reader[6].ToString()
});
}
return products;
}
catch (Exception)
{
throw;
}
finally
{
con.Close();
}
}


public static DataSet GetProductsAndCategories()
{
SqlConnection con = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("GetProducts", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
DataSet ds = new DataSet();
SqlDataAdapter adatper = new SqlDataAdapter(cmd);
adatper.Fill(ds, "Products");
cmd.CommandText = "GetCategories";
adatper.Fill(ds, "Categories");
DataRelation rel = new DataRelation("CategoryProduct", ds.Tables["Categories"].Columns["CategoryID"], ds.Tables["Products"].Columns["CategoryID"]);
return ds;
}
}
}


//实体对象
namespace ClassLibrary
{
public class Product
{
public int ProductID { get; set; }
public int CategoryID { get; set; }
public string ModelNumber { get; set; }
public string ModelName { get; set; }
public string ProductImage { get; set; }
public decimal UnitCost { get; set; }
public string Description { get; set; }


public Product(int CategoryID = 0, string ModelNumber = "",
string ModelName = "", string ProductImage = "",
decimal UnitCost=0,string Description="")
{
this.CategoryID = CategoryID;
this.ModelNumber = ModelNumber;
this.ModelName = ModelName;
this.ProductImage = ProductImage;
this.UnitCost = UnitCost;
this.Description = Description;
}
}
}