【问题标题】:WPF popup selecting template based on data type of binding基于绑定数据类型的WPF弹出选择模板
【发布时间】:2012-08-22 19:00:20
【问题描述】:

得到一个内部有很多对象的视图,这些对象从 DataTemplate 声明中获取它们的视图:

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

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

现在我想根据要包含的数据类型显示一个包含其内容的弹出窗口:

<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>

StuckHere 上的 ContentTemplateSelector 不起作用,因为它只评估一次,并且当 PopupData 更改时,不会重新选择模板。

我能找到的所有示例都依赖于默认数据模板,我不能在我的情况下使用它,因为我已经为主视图设置了默认数据模板,我只希望这个不同的模板影响我的弹出窗口。

有什么线索吗?

【问题讨论】:

  • “StuckHere 上的 ContentTemplateSelector 不起作用,因为它只评估一次并且当 PopupData 更改时,模板不会被重新选择。”这不是你想要的吗?
  • @Will - 否 - PopupData 将根据用户点击而改变,具体取决于点击的数据取决于我想要的模板。
  • @colinsmith - 第一个想法感觉非常接近,但仍然看不到如何实际将其用作我的弹出视图。弹出窗口显示为“System.Windows.DataTemplate”,就好像框架不知道如何实际呈现视图一样。我现在有另一个弹出窗口视图,所以弹出窗口内容现在是&lt;vw:myPopupView DataContext="{Binding PopupData}" /&gt;,我的视图包含两个 ControlTemplate 加上一个 DataTemplate,其中包含资源中的 Control 和 DataTemplate.Trigger 以及一个 &lt;ContentPresenter Content="{StaticResource popupDataTemplate" /&gt;。我明白为什么,但不知道该怎么做!???
  • 啊,最后一个问题是一个红鲱鱼 - 请参阅下面 Rachel 的解决方案。

标签: wpf xaml mvvm


【解决方案1】:

您可以在&lt;Popup.Resources&gt; 中应用一组不同的DataTemplates,这将覆盖在可视树中较高层定义的那些并仅应用于该Popup

<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>

【讨论】:

    【解决方案2】:

    你可以看看http://msdn.microsoft.com/en-us/library/system.windows.controls.datatemplateselector.aspx。实现从 DateTemplateSelector 派生的模板选择器并使用 ContentControl。将 Content 绑定到您的 DataObject 并将 ContentTemplateSelectorTemplate 绑定到您的 TemplateSelector。

    【讨论】:

    • 这就是问题所在 - 模板只被选择一次,如果 PopupData 的类型发生变化,模板不会随之改变,因为它只被评估一次。
    猜你喜欢
    • 2014-02-27
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2014-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多