Calvin Calvin - 1 month ago 9
C# Question

how to create listview to a grid programmatically

I have a grid with columns and rows define. By knowing x amount of items, I can add it to my xaml no problem. Unfortuantely I want to create the listview programatically because I want to populate them based on x amount of item I get when executing my SP. Here is my xaml. The label is there to assign a given content from the SP result too. Can someone show me how create this programatically?

<Grid Name="grdItems" Width="939" Grid.Row="1" HorizontalAlignment="Left" DataContext="{Binding}" Margin="5">
<Grid.RowDefinitions>
<RowDefinition Height="25"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="5"></RowDefinition>
<RowDefinition Height="25"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="5"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="231"></ColumnDefinition>
<ColumnDefinition Width="5"></ColumnDefinition>
<ColumnDefinition Width="231"></ColumnDefinition>
<ColumnDefinition Width="5"></ColumnDefinition>
<ColumnDefinition Width="231"></ColumnDefinition>
<ColumnDefinition Width="5"></ColumnDefinition>
<ColumnDefinition Width="231"></ColumnDefinition>
</Grid.ColumnDefinitions>

<Label Name="lblItem" Grid.Row="0" Grid.Column="0" Content="item label" />
<ListView Name="lstFirstItem" HorizontalAlignment="Left" VerticalAlignment="Top"
Height="auto" Margin="0,0,0,0" ItemsSource="" FontWeight="Regular"
Grid.Column="0" Grid.Row="1">
<ListView.View>
<GridView>
<GridView.ColumnHeaderContainerStyle>
<Style>
<Setter Property="FrameworkElement.Visibility" Value="Collapsed"/>
</Style>
</GridView.ColumnHeaderContainerStyle>
<GridViewColumn Width="58" DisplayMemberBinding="{Binding ItemName}"></GridViewColumn>
<GridViewColumn Width="174.25" DisplayMemberBinding="{Binding ItemDescription}"></GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</Grid>

Sai Sai
Answer

we can add rows or columns dynamically from code behind.

Inorder to add rows:

    GridLength rowheight = new GridLength(100);  //your own value we can give *,Auto as well  
    RowDefinition rowDef = new RowDefinition {Height = rowheight };    
    mainGrid.RowDefinitions.Add(rowDef);

Inorder to add colomns:

    GridLength columnwidth = new GridLength(100);        
    ColumnDefinition colDef = new ColumnDefinition { Width = columnwidth};        
    mainGrid.ColumnDefinitions.Add(colDef );    

Inorder to add textblock at particular row,column

    TextBlock textBlock = new TextBlock();        
    textBlock.Text = "Some Value";       
    Grid.SetRow(textBlock, rowNum);        
    Grid.SetColumn(textBlock, colNum);
    mainGrid.Children.Add(textBlock);  

Hope this answers your question