How can you enable automatic detection of a DataTemplate based on a data type, as you can, using a control?

We are writing a very specialized ItemsControl , which actually has three ContentPresenter per 'lines, each of which is tied to a different object (I think, a poor person’s network) instead of a more general one, such as a ListBox .

Now that the ListBox , unless you explicitly specify either an ItemTemplate or an ItemTemplateSelector , there seems to be an internal selector that applies a template based solely on the data type. However, our ContentPresenter do not collect them. We also tried switching them to ContentControl , but that didn't work either.

Now I know that I can just write my own DataTypeTemplateSelector that does this, but I wonder if this function has already been β€œbaked” somewhere, it was thought that it is used with many ItemsControl ( ListBox , TreeView , ComboBox ', DataGrid , etc.) .d.) and in accordance with this MSDN article ...

http://msdn.microsoft.com/en-us/library/ms742521.aspx

... it should work by default! But then again, this is not so.

Here is 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 ... someone wants to take a hit, why not?

+8
wpf datatemplate contentpresenter contentcontrol
source share
1 answer

DataType , for some crazy reason , is of type Object , DataTemplates therefore have a string value in this property if you are not using x:Type .


Edit: There is a very good reason why a property is an object, as always those who can (and do) read clearly have an advantage:

If the template is intended for object data, this property contains the name of the data object type (as a string). To refer to the type of the class name, use the x: Type markup extension. If the template is for XML data, this property contains the name of the XML element. For more information about specifying a namespace other than the default value for an XML element, see the documentation.

+6
source share

All Articles