Search code examples
c#wpfdatagrid

Is it possible to fill a Datagrid source from a method call but only use parts of the returned list?


Sorry, very new to Datagrids. I like the idea of filling a Datagrid source from a method call like this:

AWin.PredicateStatementDataGrid.ItemsSource = Tactics.GeneratePredicateStatements();

But unfortunately, it's overwriting how I want the datagrid to look (I've manually set column headers and widths):

<DataGrid Name="PredicateStatementDataGrid" GridLinesVisibility="All"  HeadersVisibility="All">
         <DataGrid.Columns>
            <DataGridTemplateColumn Header="ID #" Width="35" IsReadOnly="True">
                </DataGridTemplateColumn>
                <DataGridTemplateColumn Header="Predicate Statement" Width="300" IsReadOnly="True">
            </DataGridTemplateColumn>
         </DataGrid.Columns>
</DataGrid>

But this is what the output looks like: enter image description here

I don't want the method call to create a second set of columns and I really don't want IsBold displayed (I want to use it as a boolean to set bold type as described here).

So, is it possible to fill a datagrid from a method call but only use some of the elements in the returned List? And is it possible to not overwrite my manually set columns and headers?

Thanks in advance!


Solution

  • First you need to set AutogenerateColumns to false. Then you need to bind the columns to the properties in your collection.

    <DataGrid Name="PredicateStatementDataGrid" GridLinesVisibility="All"  
              HeadersVisibility="All" AutoGenerateColumns="false">
        <DataGrid.RowStyle>
            <Style TargetType="DataGridRow">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsBold}" Value="true">
                        <Setter Property="Fontweight" Value="Bold"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        <DataGrid.Columns>
            <DataGridTextColumn Header="ID #" Width="35" IsReadOnly="True"
                Binding="{Binding ID}">
            </DataGridTextColumn>
            <DataGridTextColumn Header="Predicate Statement" Width="300" 
                Binding="{Binding Statement}">
                IsReadOnly="True">
            </DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>