c# - 使用 C# 在每一行中动态地将 Button 添加到 ListView

标签 c# wpf listview

我有一个 ListView,我必须在其中显示从我的数据库表中提取的所有行。同样,我必须在每行中提供两个编辑和删除按钮。因为我是初学者,所以我在 XAML 中尝试了以下代码-

<ListView Height="352" HorizontalAlignment="Left" Margin="20,90,0,0" Name="Tab1lstProductCategories" VerticalAlignment="Top" Width="1008">
                        <ListView.View>
                            <GridView>
                                <GridViewColumn Header="Category Name" DisplayMemberBinding="{Binding Col1}" Width="200"/>
                                <GridViewColumn Header="Created Date" DisplayMemberBinding="{Binding Col2}" Width="200"/>
                                <GridViewColumn Header="Last Updated" DisplayMemberBinding="{Binding Col3}" Width="200"/>
                                <GridViewColumn Header="Edit" Width="200">
                                    <GridViewColumn.CellTemplate>
                                        <DataTemplate>
                                            <Button Content="Edit" Click="EditCategory" CommandParameter="{Binding Id}"/>
                                        </DataTemplate>
                                    </GridViewColumn.CellTemplate>
                                </GridViewColumn>
                                <GridViewColumn Header="Delete" Width="200">
                                    <GridViewColumn.CellTemplate>
                                        <DataTemplate>
                                            <Button Content="Delete" Click="DeleteCategory"/>
                                        </DataTemplate>
                                    </GridViewColumn.CellTemplate>
                                </GridViewColumn>
                            </GridView>
                        </ListView.View>
                    </ListView>

我用 C# 写了-

 DataTable dt=db.Select("select * from ProductCategories");
           for (int i = 0; i < dt.Rows.Count; i++)
        {
            //Button edit, delete;
            //edit = new Button();
            //edit.Content="Edit";
            //edit.Click += EditCategory;
            //delete= new Button();
            //delete.Content="Delete";
            //delete.Click += DeleteCategory;
            //edit.CommandParameter = dt.Rows[i]["Id"];
            //delete.CommandParameter = dt.Rows[i]["Id"];
            Tab1lstProductCategories.Items.Add(new { Col1 = dt.Rows[i]["CategoryName"], Col2 = dt.Rows[i]["CreatedDate"], Col3=dt.Rows[i]["LastUpdated"]});                
        }



private void EditCategory(object sender, RoutedEventArgs e)
        {
            Button b=sender as Button;
            MessageBox.Show(b.CommandParameter.ToString());
        }

    private void DeleteCategory(object sender, RoutedEventArgs e)
    {
    }

我得到的结果是—— enter image description here

我想要那边的按钮,请帮帮我。

最佳答案

好的,我发现您的代码存在一些问题。

1) 你真的应该像@HighCore 建议的那样创建一个合适的数据类型。查看您的代码,我认为它看起来像这样:

public class ProductCategory
{
    public int Id { get; set; }

    public string CategoryName { get; set; }

    public DateTime CreatedDate { get; set; }

    public DateTime LastUpdated { get; set; }
}

然后创建ProductCategory的集合,而不是直接添加匿名类型

DataTable dt=db.Select("select * from ProductCategories");

// Create a collection for your types
ObservableCollection<ProductCategory> list = new ObservableCollection<ProductCategory>();

for (int i = 0; i < dt.Rows.Count; i++)
{
    ProductCategory productCategory = new ProductCategory
    {
        // Casting might be needed here depending on your data types ...
        Id = dt.Rows[i]["Id"],
        CategoryName = dt.Rows[i]["CategoryName"],
        CreatedDate = dt.Rows[i]["CreatedDate"],
        LastUpdated = dt.Rows[i]["LastUpdated"]
    };

    list.Add(productCategory);
}

2) 您直接将项目添加到 ListView,这是错误的。您应该做的是将您的集合设置为 ListViewItemsSource

Tab1lstProductCategories.ItemsSource = list;

3) 使用后CellTemplate要通过 xaml 实现 ListView 想要的外观并更改 DisplayMemberBinding 绑定(bind)到适当的属性,您可以通过默认 绑定(bind) CommandParameter {Binding} 表达式,它将命令参数设置为其代表的 ProductCategory 项目。

    <ListView Height="352" HorizontalAlignment="Left" Margin="20,90,0,0" Name="Tab1lstProductCategories" VerticalAlignment="Top" Width="1008">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Category Name" DisplayMemberBinding="{Binding CategoryName}" Width="200"/>
                <GridViewColumn Header="Created Date" DisplayMemberBinding="{Binding CreatedDate}" Width="200"/>
                <GridViewColumn Header="Last Updated" DisplayMemberBinding="{Binding LastUpdated}" Width="200"/>
                <GridViewColumn Header="Edit" Width="200">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <Button Content="Edit" Click="EditCategory" CommandParameter="{Binding}"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Header="Delete" Width="200">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <Button Content="Delete" Click="DeleteCategory" CommandParameter="{Binding}"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>

从事件处理程序 - EditCategoryDeleteCategory,您可以提取 ProductCategory 的 ID

private void EditCategory(object sender, RoutedEventArgs e)
{
    Button b=sender as Button;
    ProductCategory productCategory = b.CommandParameter as ProductCategory;
    MessageBox.Show(productCategory.Id);
}

这应该足以使您的代码正常工作,但我还想说明其他几点

一个。您应该高度考虑使用 MVVM图案。这将意味着不在代码中使用事件处理程序,而是使用 Commands相反,并按照其最初打算使用的方式使用 CommandParameter

考虑一些 ORM框架而不是将数据库直接绑定(bind)到您的 UI。这会产生令人难以置信的紧密耦合,这将使您的代码的可重用性和灵 active 大大降低。

希望对你有帮助

关于c# - 使用 C# 在每一行中动态地将 Button 添加到 ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19361940/

相关文章:

android - addTextChangedListener() 多次触发,并且针对 ListView 中的所有 edittext 字段

c# - 将枚举映射到 "sub-enum"

c# - C# winform如何检查SQL Server数据库中是否存在一条记录?

c# - 在 XAML 中将数据绑定(bind)到 TreeView

c# - 通过 Webhook C# 发送 Discord 嵌入

android - 需要获取 id 而不是 position

c# - 如何从多维 PSafeArray 获取数据?

c# - 找不到类型或命名空间名称 'Class1'(是否缺少 using 指令或程序集引用?)

wpf - 如何在 WPF 中使用 XAML 设置 ComboBox header

android - 空 ListView,如何在 ListView 为空时显示消息?