开发者

How can you enable auto-DataTemplate selection based on data type like you can with an items control?

开发者 https://www.devze.com 2023-04-08 15:52 出处:网络
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

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,
      开发者_StackOverflow社区   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?


DataType, for whatever crazy reason, is of type Object, the DataTemplates hence have a string set in that property unless you use x:Type.


Edit: There is a very good reason for the property being an object, as always those who can (and do) read are clearly at an advantage:

If the template is intended for object data, this property contains the type name of the data object (as a string). To refer to the type name of the class, use the x:Type Markup Extension. If the template is intended for XML data, this property contains the XML element name. See the documentation remarks for details about specifying a non-default namespace for the XML element.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号