Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF popup selecting template based on data type of binding

Tags:

mvvm

wpf

xaml

Got a view with lots of objects inside, which get their View from a DataTemplate declaration:

<DataTemplate DataType="{x:Type vm:StatusAViewModel}" >
    <vw:StatusAView />
</DataTemplate>

<DataTemplate DataType="{x:Type vm:StatusBViewModel}" >
    <vw:StatusBView />
</DataTemplate>

Now I want to show a popup with its content based on the type of the data it's to contain:

<Popup AllowsTransparency="True"
       IsOpen="{Binding IsPopupOpen,Mode=OneWay}" 
       PlacementTarget="{Binding PopupPlacementElement}" Placement="{Binding PopupPlacementMode}"
       HorizontalOffset="{Binding PopupHOffset}" VerticalOffset="{Binding PopupVOffset}">
    <ContentPresenter x:Name="StuckHere" Content="{Binding PopupData}" />
</Popup>

A ContentTemplateSelector on StuckHere doesn't work because it's only evaluated once and when the PopupData changes, the template isn't re-selected.

All the examples I can find rely on a default datatemplate, which I can't use in my case because I've already got a default DataTemplate for the main view, I only want this different template to affect my popup.

Any clues?

like image 752
AndyC Avatar asked Oct 27 '25 06:10

AndyC


1 Answers

You can apply a different set of DataTemplates in <Popup.Resources>, which will override the ones defined higher up in the visual tree and apply to that Popup only

<Window.Resources>
    <DataTemplate DataType="{x:Type vm:StatusAViewModel}" >
        <vw:StatusAView />
    </DataTemplate>
    <DataTemplate DataType="{x:Type vm:StatusBViewModel}" >
        <vw:StatusBView />
    </DataTemplate>
</Window.Resources>

<Popup>
    <Popup.Resources>
        <DataTemplate DataType="{x:Type vm:StatusAViewModel}" >
            <vw:StatusAPopupView />
        </DataTemplate>
        <DataTemplate DataType="{x:Type vm:StatusBViewModel}" >
            <vw:StatusBPopupView />
        </DataTemplate>
    </Popup.Resources>

    <!-- The DataTeplate used here will be a PopupView, not the regular View -->
    <ContentPresenter Content="{Binding PopupData}" />
</Popup>
like image 53
Rachel Avatar answered Oct 29 '25 06:10

Rachel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!