We're writing a very specialized ItemsControl
which actually has three ContentPresenter
's per 'row', each bound to a different object (think poor-man's grid) instead of the more common one, like a ListBox
.
Now with a ListBox
if you don't explicitly specify either an ItemTemplate
or an ItemTemplateSelector
, there seems to be some internal selector that applies the template based purely on data type. However, our ContentPresenter
's aren't picking them up. We've also tried switching them to ContentControl
's instead, but that hasn't worked either.
Now I know I can simply write my own DataTypeTemplateSelector
that does this, but I'm wondering if that functionality is already 'baked in' somewhere considered its used with so many ItemsControl
's (ListBox
, TreeView
, ComboBox
', DataGrid
, etc.) and according to this MSDN article...
http://msdn.microsoft.com/en-us/library/ms742521.aspx
...it should work by default! But again, it doesn't.
Here's our (pseudo) code...
<UserControl.Resources>
<!-- These all work when the relevant items are in a ListBox,
but not with stand-alone ContentPresenters or ContentControls -->
<DataTemplate DataType="local:SomeTypeA">
<TextBlock Text="{Binding Converter={c:DataTypeNameConverter}}" Foreground="Blue" />
</DataTemplate>
<DataTemplate DataType="local::SomeTypeB">
<TextBlock Text="{Binding Converter={c:DataTypeNameConverter}}" Foreground="Purple" />
</DataTemplate>
<DataTemplate DataType="local::SomeTypeC">
<TextBlock Text="{Binding Converter={c:DataTypeNameConverter}}" Foreground="Purple" />
</DataTemplate>
</UserControl.Resources>
<!-- These don't pick up the templates -->
<ContentControl Content="{Binding Field1}" />
<ContentPresenter Content="{Binding Field2}" />
<!-- This however does -->
<ListBox ItemsSource="{Binding AllItems}"
So... anyone want to take a stab at why not?
DataTemplates
withContentControls
many times in the past without a problem. Can you post your actual code instead of pseudocode? And does it work if you set DataType equal to{x:Type local:SomeTypeA}
instead of just"local:SomeTypeA"
? – Squamax:Type
for the reason that H.B. pointed out below... MSFT in their infinite wisdom deemed a property called 'DataType' is of typeObject
and not of typeSystem.Type
so unlike with the 'TargetType' of a style, for a DataTemplate you have to use the markup. – Pirouette