I’m porting a Silverlight application to WPF for a project at work, and I’ve run into a small cosmetic issue. In the Silverlight application, the Datagrid’s ItemsSource is an ObservableCollection that is initially empty. When I first load the application, the column headers are displayed, even though the DataGrid itself is empty. I am now trying to achieve the same thing in the WPF application. The ObservableCollection and Datagrid are both the same, but now the column headers only appear when I add a row to the Datagrid. The XAML for my Datagrid is as follows:
<DataGrid ColumnWidth="196" GridLinesVisibility="All"
AutoGenerateColumns="True" IsReadOnly="True" HorizontalAlignment="Center"
Height="375" Width="775" ItemsSource="{Binding source}"
RowBackground="#A5BACA" AlternatingRowBackground="LightGray"
VerticalAlignment="Center" Name="documentsDG"
FontWeight="Normal" FontSize="13" HeadersVisibility="Column"
Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="4">
</DataGrid>
Like I said, adding and removing rows works fine, it’s just that I would like to find a way to make the column headers display without any data in the Datagrid. Also, I’ve tried starting the application with an empty row in the Datagrid, which does make the column headers appear, but it looks messy. If I remove that row from within the application, the column headers remain, but if I remove it on window load, they disappear.
So, any help would be appreciated. Let me know if you need anything more on my end.
You’re autogenerating the columns. If you manually define the columns they’ll be visible even when your collection is empty.
Also see:
WPF Toolkit Datagrid Headers and Empty Source