Reputation: 127
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
Upvotes: 1
Views: 2857
Reputation: 644
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..
Upvotes: 1