How can I stop an implicit TextBox style from getting inherited in a ComboBox when DisplayMemberPath is not set?

StackOverflow https://stackoverflow.com/questions/12204212

  •  29-06-2021
  •  | 
  •  

Question

I have two ComboBoxes. One is bound to a list of enum values, while the other is bound to a list of custom class objects and has the DisplayMemberPath property set.

The ComboBox bound to the enum values applies an implicit TextBlock style, while the ComboBox that uses the DisplayMemberPath property does not.

Using Snoop I can verify that both ComboBoxes are rendered with the exact same set of controls (a <ContentPresenter> containing a <TextBlock>), however the TextBlock in the ComboBox without the DisplayMemberPath set contains a Margin of 5 while the one with DisplayMemberPath set does not.

<Grid.Resources>
    <Style TargetType="{x:Type TextBlock}">
        <Setter Property="Margin" Value="5" />
    </Style>
</Grid.Resources>

<ComboBox Grid.Row="0" Grid.Column="1" 
          ItemsSource="{Binding EnumCollection}" 
          SelectedItem="{Binding SelectedEnum}" />

<ComboBox Grid.Column="1" Grid.Row="2" 
          ItemsSource="{Binding SomeCollection}" 
          SelectedItem="{Binding SelectedItem}"
          DisplayMemberPath="Name" />

Screenshot

Why is this? And what can I do to stop the Enum ComboBox from inheriting the implicit TextBlock style?

Was it helpful?

Solution

My assumption would be that the DisplayMemberPath creates a DataTemplate, and styles will not be applied within its scope.

Try setting DisplayMemberPath="." to make the first ComboBox use a DataTemplate containing <TextBlock Text="{Binding .}">, which will prevent the implicit style from getting applied.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top