WPF DataGridTemplateColumn添加按鈕和按鈕事件獲取行參數


在開發軟件過程中有一些客戶要求要在表個里面添加一列“狀態列”在這列里面添加有按鈕,這些按鈕有“刪除、編輯、停用、啟用、修改、詳細內容等等”。開發人員為了瞞足看客戶的需求從而開發表格里面添加按鈕的需求,每一行的按鈕只能對他所在的一行進行操作,不能操作別的行的內容。
下面的的代碼是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)
        {
           
        }

下圖運行的碼的效果截圖

在這里插入圖片描述

以上是本人參考了一些網上的資料做出的一個案例,如有不足的地方請指出、我會思考問題修改不足的地方。

 

出處:https://blog.csdn.net/weixin_42104218/article/details/97415042

 

注意:

這里建議按鈕的綁定使用  <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>)

            //其他邏輯代碼,本處省略。。。

        }

 

 

出處:https://blog.csdn.net/destiny_98/article/details/102950585

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

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;         }     } }

 

 

出處:https://blog.csdn.net/dxm809/article/details/79785923

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM