我向 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/