【问题标题】:DataTemplates in resource dictionaries don't inherit from app.xaml styles?资源字典中的 DataTemplates 不继承自 app.xaml 样式?
【发布时间】:2023-03-16 22:56:02
【问题描述】:

我在 app.xaml 中添加了自定义命名样式。

我创建了一个外部资源字典(我附加在 app.xaml 的合并字典中),当我尝试在 rcource 字典中使用上述命名样式之一时,它说没有这样的样式。

此外,默认样式(即适用于整个应用程序的未命名样式)不适用于模板元素。

注意:模板的 Build Action 是 'Page'。


这是我的代码编写方式的示例:

<Application x:Class="Application"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    
    ShutdownMode="OnExplicitShutdown">
    <Application.Resources>
        <ResourceDictionary>

            <Style
                    x:Key="StackPanelStyle" 
                    TargetType="StackPanel" 
                    BasedOn="{StaticResource {x:Type StackPanel}}">
                <Setter Property="Margin" Value="5"/>
                <Setter Property="Orientation" Value="Horizontal" />
                <Setter Property="Height" Value="40"/>
            </Style>

            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/Templates/DataTemplate1.xaml"/>
                <ResourceDictionary Source="/Templates/DataTemplate2.xaml"/>
                <ResourceDictionary Source="/Templates/DataTemplate3.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

这是一个数据模板的例子:

<DataTemplate DataType="{x:Type Entity}" x:Key="NameDataTemplate">
    <Expander>
        <StackPanel>
            <--The following line produces: StackPanelStyle was not found.-->
            <StackPanel Style="{StaticResource StackPanelStyle}">
                <Label Content="Name:"/>
                <TextBox Text="{Binding Name}"/>
            </StackPanel>
        </StackPanel>
    </Expander>
</DataTemplate>

有什么想法吗? 我必须以不同的方式合并字典吗?

【问题讨论】:

  • 只是出于好奇,NameDataTemplate存储在哪个资源字典文件中?
  • 这只是一个例子,我的意思是强调样式在合并DataTemplates之前出现在app.xaml中。

标签: wpf styles resourcedictionary app.xaml


【解决方案1】:

代码无法正常运行,因为资源字典中的 DataTemplate 不知道是哪一个在使用它,它只是使用过。像好莱坞模式。他们分别编译。

要完成这项工作,您可以将 app.xaml 中的样式放在 DataTemplate 的同一资源字典中,或者如果您不喜欢这种耦合,则可以将其放在不同的资源字典中,并且将其合并到 DataTemplate 的资源字典中

【讨论】:

  • :D,又名。 “别给我打电话,我给你打电话。”因此,资源字典不知道哪个会调用它,因此它不知道它之外的样式。
  • 你很好......“你可以把它放在不同的资源字典中,并将它合并到 DataTemplate 的资源字典中。” - 这是我用的。我认为这是最合适的答案,所以不妨将其加粗或放在答案之上,以便人们第一眼就能看到。
【解决方案2】:

App.xaml 的构建操作应为 ApplicationDefinition,资源字典文件的构建操作应为 Page。我猜你这两个都是正确的,因为它们是默认的(我看到你已经提到过 Page)。

我想不出你的情况还有什么其他问题。只要您的静态资源以正确的顺序定义(它们看起来是这样),它就应该能够在您运行应用程序时找到它们。

编辑

调试思路:使用简单的按钮样式创建一个名为“TestDictionary.xaml”的新资源字典。确保此词典与您的其他词典(DataTemplate1.xaml 等)位于同一文件夹中。在MergedDictionaries 中仅添加指向 TestDictionary 的链接(注释掉其他链接)。在您的启动窗口上放置一个按钮并应用该样式。看看这是否有效。如果它失败了,你就知道你的合并有问题。如果成功,您的DataTemplate 可能是问题所在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-06
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多