使用C#在每行中将Button动态添加到ListView [英] Add Button to ListView dynamically in each row using C#

查看:98
本文介绍了使用C#在每行中将Button动态添加到ListView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a ListView in which I have to show all rows fetched from my database table. Again I have to give two edit and delete buttons in each row. As I am beginner for the same, I tried the following code in 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#中我写了

And in C# I Wrote-

 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)
    {
    }

我得到的结果是-

我要在那边按钮,请帮帮我.

I want button over there, Please help me out.

推荐答案

好的,所以我发现您的代码有几个问题.

Ok, so I see a couple of issues with your code.

1)您确实应该创建一个建议的类似@HighCore的数据类型.查看您的代码,我想它将看起来像这样:

1) You really should create a proper datatype like @HighCore suggested. Looking at your code I assume it will look something like this:

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

    public string CategoryName { get; set; }

    public DateTime CreatedDate { get; set; }

    public DateTime LastUpdated { get; set; }
}

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

Then create a collection of ProductCategory instead of directly adding anonymous types

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.

2) You are directly adding item's to the ListView which is wrong. What you should be doing is set your collection to be the ItemsSource of your ListView.

Tab1lstProductCategories.ItemsSource = list;

3)使用 CellTemplate 通过xaml实现ListView所需的外观并将DisplayMemberBinding绑定更改为适当的属性,您可以通过默认的{Binding}表达式绑定CommandParameter,该表达式会将命令参数设置为它代表的项目.

3) After using CellTemplate to achieve the ListView wanted look through xaml and changing the DisplayMemberBinding binding to the appropriate properties, you can bind the CommandParameter through the default {Binding} expression which will set the command parameter to be the ProductCategory item it represents.

    <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

From the event handlers - EditCategory and DeleteCategory, you can extract the Id of the ProductCategory

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

这应该足以使您的代码正常工作,但是我还要指出其他几点

This should be sufficient to make your code work, but there are several other points I'd like to make

a.您应该高度考虑使用 MVVM 模式.这将意味着不在代码后面使用事件处理程序,而是使用命令,并使用CommandParameter最初使用的方式.

a. You should highly consider using MVVM pattern. this will mean not using event handlers in code behind but using Commands instead, and use CommandParameter the way it was originally intended to be used.

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

b. Consider some ORM framework instead of binding the database directly to your UI. this create incredibly tight coupling which will make your code a lot less reusable, and flexible.

希望这会有所帮助

这篇关于使用C#在每行中将Button动态添加到ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆