2

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?

Rachel
  • 130,264
  • 66
  • 304
  • 490
  • 1
    My assumption would be that the `DisplayMemberPath` creates a `DataTemplate`, styles will not be applied within its scope. – H.B. Aug 30 '12 at 19:39
  • @H.B. It does... per [MSDN](http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.displaymemberpath.aspx) "This property is a simple way to define a default template that describes how to display the data objects". I know I can do some obnoxious ugly workaround with `` but I was hoping for a cleaner solution. – Rachel Aug 30 '12 at 19:44
  • @KDiTraglia That would make both `ComboBoxes` inherit the implicit `TextBlock` style, and I wanted the reverse: for both of them to *not* inherit it. – Rachel Aug 30 '12 at 19:48

1 Answers1

2

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.

Rachel
  • 130,264
  • 66
  • 304
  • 490
H.B.
  • 166,899
  • 29
  • 327
  • 400
  • I knew you'd know the answer to this ^_^ That works fine, thank you – Rachel Aug 30 '12 at 19:50
  • It is more like i guessed it :) – H.B. Aug 30 '12 at 19:50
  • Nothing wrong with that :) I find a disturbingly large percentage of my programming is just educated guesses. Or as I call it, "educated trial-and-error". – Rachel Aug 30 '12 at 19:53
  • @Rachel: Well, if you have a deep understanding of the system, the guesses become predictions. Here i just thought that `DisplayMemberPath` causes `{Binding }` so `{Binding .}` should work. – H.B. Aug 30 '12 at 20:03