简体   繁体   中英

How to add Checkboxes to Listview from Code behind using C# in WPF

I am populating a listview from code behind, why I am doing this scenario is, I need to create columns dynamically from code behind(one column,two,three....). My code looks like below

XAML Code :

<ListView  ItemsSource="{Binding}" Name="lvLOv" Width="400"></ListView>

C# Code:

Output:

在此处输入图片说明

But I need to place checkboxes before every row like as below(I need to do this in code behind like above code/ integrate the checkbox code in the above code). I need to place checkall option also in the header

public TestForm() { this.InitializeComponent(); Test(); }

public void Test()
{
    try
    {
        DataTable dt = new DataTable();

        //Create Columns
        dt.Columns.Add("Initial", typeof(string));
        dt.Columns.Add("Name", typeof(string));

        //Adding Rows
        for (int i = 0; i < 3; i++)
        {
            dt.Rows.Add("K" + i, "David" + i);
        }

        GridView gv = new GridView();


        // Create the GridView Columns
        foreach (DataColumn item in dt.Columns)
        {
            GridViewColumn gvc = new GridViewColumn();
            gvc.DisplayMemberBinding = new Binding(item.ColumnName);
            gvc.Header = item.ColumnName;
            gvc.Width = Double.NaN;
            gv.Columns.Add(gvc);
        }

        lvLOv.View = gv;

        //Binding to Listview
        lvLOv.DataContext = dt.DefaultView;

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

}

Expected Output:

在此处输入图片说明

Can you please let me know how can I achieve this functionality

Its really easy just do this..

In Design view (Xaml):

<Window.Resources> 
   <DataTemplate x:Key="Chk_Field" DataType="{x:Type GridViewColumn}">
      <CheckBox IsChecked="{Binding chk}" />
   </DataTemplate>
</Window.Resources>

In Code behind:

GridView gridview = new GridView();
Window window = Application.Current.MainWindow;
DataTemplate s = (DataTemplate)window.FindResource("Chk_Field");
gridview.Columns.Add(new GridViewColumn { Header = "Head", CellTemplate = s });

By doing this you can change the celltemplate for each column in code behind..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM