【问题标题】:WPF how to set the datatemplates of a contentcontrol?WPF如何设置内容控件的数据模板?
【发布时间】:2014-12-16 21:21:33
【问题描述】:

我对以下代码示例的工作方式感到非常困惑。似乎 Contentcontrol 从窗口资源中获取数据模板。

contentcontrol 没有自己的“内容模板”来确定其中的视图吗?如果没有设置任何内容,它是否只是向上搜索并将其内容设置为数据模板?

我可能混淆了这两个术语,但我真的很困惑为什么该示例将数据模板存储在窗口资源级别。

无论如何,我想了解我有哪些选项可以为给定窗口设置视图。最初我打算只使用一个内容控件并在其中托管视图,但后来我想知道是否可能有理由让内容控件选择一个页面(从实际页面类)而不是一个视图(扩展用户控制)。

   <Window.Resources>
        <DataTemplate DataType="{x:Type local:HomeViewModel}">
            <local:HomeView />
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:ProductsViewModel}">
            <local:ProductsView />
        </DataTemplate>
    </Window.Resources>


<DockPanel>
    <Border DockPanel.Dock="Left" BorderBrush="Black" BorderThickness="0,0,1,0">
        <ItemsControl ItemsSource="{Binding PageViewModels}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button Content="{Binding Name}"
                            Command="{Binding DataContext.ChangePageCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
                            CommandParameter="{Binding }"
                            Margin="2,5"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Border>

    <ContentControl Content="{Binding CurrentPageViewModel}" />
</DockPanel>

【问题讨论】:

    标签: wpf xaml mvvm navigation


    【解决方案1】:

    由于DataType 属性,它可以工作。如果 DataTemplate 指定 DataType(没有 Key),则运行时会将该类型的对象与模板匹配。

    contentcontrol 没有自己的“contenttemplate”来确定其中的视图吗?

    确实如此,但如果它没有设置其ContentTemplate 属性,则运行时会寻求应用与该类型匹配的 DataTemplate。 MSDN 文档与Style 元素上的TargetType 进行了类比——您可以在本地应用样式,但也可以将样式全局应用于特定类型。例如,使用&lt;Style TargetType="{x:Type Button}"&gt; 将该样式应用于范围内的所有按钮。同样,&lt;DataTemplate DataType="{x:Type local:HomeViewModel}"&gt; 将该模板应用于所有类型为“HomeViewModel”的内容。

    如果没有设置,它是否只是向上搜索并将其内容设置为数据模板?

    有点,是的。它搜索当前资源,其中包括从父资源字典继承的资源键。

    我可能混淆了这两个术语,但我真的很困惑为什么该示例将数据模板存储在窗口资源级别。

    这并不重要——您可以将它们存储在应用程序级别,甚至可以存储在ContentControl 中。

    【讨论】:

      猜你喜欢
      • 2011-08-11
      • 1970-01-01
      • 2011-01-22
      • 1970-01-01
      • 1970-01-01
      • 2011-07-22
      • 1970-01-01
      • 1970-01-01
      • 2012-02-16
      相关资源
      最近更新 更多