wpf - 资源字典中的 DataTemplate 不继承自 app.xaml 样式?

标签 wpf styles resourcedictionary app.xaml

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

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

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

注意:模板的构建操作是“页面”。


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

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

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

最佳答案

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

要实现此目的,您可以将 app.xaml 中的样式放入 DataTemplate 的同一资源字典中,或者如果您不喜欢这种耦合,则可以将其放入不同的资源字典中,并且将其合并到 DataTemplate 的资源字典中

关于wpf - 资源字典中的 DataTemplate 不继承自 app.xaml 样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1664658/

相关文章:

wpf - 如何在 xamarin.froms 中为 WPF 中的图像添加鼠标事件的缩放功能

wpf - UserControl 根据数据类型更新图像

c# - 重新绑定(bind)新数据源时 DataGrid 不更新

javascript - 如何在点击头部时更改样式?

html - 如何更改 chhtml 中的操作链接按钮样式

javascript - Fancybox 的多个实例的自定义样式

c# - 如何使用资源两次?

wpf - 将标记扩展编写为嵌套元素

c# - 适用于 WPF 的 Microsoft .NET 图表控件

wpf - 有没有办法让 DynamicResource 对于 ResourceDictionary 中的 Freezable 是动态的?