Based on this SO question, I've created a combobox with 2 columns, and a header. However, I needed the columns to be proportionally spaced, so I removed the shared size groups, and changed the width to "*"
. To stretch the the grid, I added the HorizontalContentAlignment
on the ComboBox
itself. See below for the complete xaml
.
This worked for the rows with the actual data, but the headers kept left aligned. However, when I was inspecting it with Snoop, I noticed that the headers were fine.
Apparently, when I select the ComboBoxItem
, which contains the header, the layout gets corrected (hence, the heisenbug).
Any ideas why this happens? How would you troubleshoot this? Do have the wrong approach in making the layout proportionally spaced?
The ComboBox looks like this. The employee is a simple POCO, and the collection a subclass of Collection<Employee>
to make it work in the XAML. The full project can be found in this gist.
To reproduce this:
- start the application
- start Snoop, and inspect the application
- open the comboBox, and inspect an element
select the first ComboBoxItem
<ComboBox Name="cb" ItemsSource="{DynamicResource items}" HorizontalContentAlignment="Stretch"> <ComboBox.DataContext> <obj:EmployeeCollection> <obj:Employee Name="John" Occupation="Developer" /> <obj:Employee Name="Jack" Occupation="Spy" /> </obj:EmployeeCollection> </ComboBox.DataContext> <ComboBox.Resources> <CompositeCollection x:Key="items"> <ComboBoxItem IsEnabled="False"> <Grid TextElement.FontWeight="Bold"> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Grid.Children> <TextBlock Grid.Column="0" Text="Name"/> <TextBlock Grid.Column="1" Text="Occupation"/> </Grid.Children> </Grid> </ComboBoxItem> <Separator/> <CollectionContainer Collection="{Binding Source={x:Reference cb}, Path=DataContext}"/> </CompositeCollection> <DataTemplate DataType="{x:Type obj:Employee}"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Grid.Children> <TextBlock Grid.Column="0" Text="{Binding Name}"/> <TextBlock Grid.Column="1" Text="{Binding Occupation}"/> </Grid.Children> </Grid> </DataTemplate> </ComboBox.Resources> </ComboBox>