WPF自定义控件模板未应用

6

我相信这个问题或类似的问题已经被问了无数次,但我找不到任何能帮助我解决问题的东西,所以我在这里提问。请随意指导我去重复,我相信它存在,但我找不到。显然我的关键字不是很好。

我有一个自定义控件,它有自己的资源字典,仅用于定义控件模板。然后将此字典合并到Generic.xaml中。

问题是当这个控件出现在UI中时,它里面没有任何东西。我使用Snoop来发现这一点。控件在UI中,但是它是完全空的。

下面是我认为负责这个问题的部分。非常感谢您能提供的任何帮助或建议。

我的文件夹结构的相关部分如下:

My Directory Structure

BasicTemplate.xaml:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WPFSpecBuilder.Layouts.Templates">

    <Style TargetType="{x:Type local:BasicTemplate}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:BasicTemplate}">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}">
                        <Grid>
                            <TextBlock Text="This is a basic template." />
                        </Grid>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

Generic.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="Layouts/Templates/XAML/BasicTemplate.xaml" />
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

我会采用排除法来解决问题:首先确认您的样式定义不是问题的一部分。因此,将其从嵌套的ResourceDictionary中挑选出来并放入Generic.xaml中(我希望您在App.xaml中引用它)。在显示所需效果之后,尝试Steve提出的方法(确认相对路径设置正确)。 - Sebastian Edelmeier
3个回答

1

我认为这可能只需要更改合并字典的相对路径。尝试在文件夹路径的开头添加/

<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="/Layouts/Templates/XAML/BasicTemplate.xaml" />
</ResourceDictionary.MergedDictionaries>

1

1

请尝试以下操作:

  1. 将 Build Action 设置为 BasicTemplate.xaml 并设置为 Page。

  2. 在 Generic.xaml 中添加对 BasicTemplate.xaml 的引用:

    ResourceDictionary Source="/WPDSpecBuilder;component/Layouts/Templates/Xaml/BasicTemplate.xaml"

这样应该就可以了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接