【问题标题】:How to reference Custom WPF Control in generic.xaml如何在 generic.xaml 中引用自定义 WPF 控件
【发布时间】:2016-08-09 03:19:07
【问题描述】:

我正在尝试创建一个继承自标准 TextBlock 的自定义 WPF 控件,如下所示:

public class DynamicDateTextBlock : TextBlock
{
    static DynamicDateTextBlock()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(DynamicDateTextBlock), new FrameworkPropertyMetadata(typeof(DynamicDateTextBlock)));
    }
}

相应的 generic.xaml 如下所示:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:Test">
    <Style TargetType="{x:Type local:DynamicDateTextBlock}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:DynamicDateTextBlock}">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}" />
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

如果我将 control.cs 放在我的解决方案测试的根目录中,一切正常。 但是,如果我将它移动到子文件夹 Test\Controls 并相应地更改命名空间,那么 generic.xaml 就会出现编译错误

命名空间“clr-namespace:Test.Controls”中不存在名称“DynamicDateTextBlock”

cs 命名空间更改为 Test.Controls

在 xaml 中我尝试像这样使用它:xmlns:local="clr-namespace:Test.Controls"

还有什么我必须做的吗?

使用 Resharper 重构控件以移动它会产生同样的问题。

【问题讨论】:

    标签: wpf xaml namespaces declaration resourcedictionary


    【解决方案1】:

    当您将DynamicDateTextBlock 移动到Controls 文件夹并更改xmlns:local="clr-namespace:Test.Controls" 后尝试重建并运行您的应用程序,即使出现错误。应启动应用程序。你所有的行为都是正确的。

    更新: 更改 xaml xmlns:local="clr-namespace:Test.Controls" 后,您应该再次手动键入。我是手写的,没有错误。

    【讨论】:

    • 我是这么想的,但是在我移动控件后它不再编译了:There were build errors. 尝试运行后,错误列表又显示了一个:Cannot find the Style Property 'Template' on the type 'Test.Controls.DynamicDateTextBlock'. Line 5 Position 17.
    • @Mikk 请看我更新的答案。欢迎提出任何问题。
    • 这很奇怪,对我来说,即使在一个新的、否则为空的解决方案中手动操作也无法正常工作。自动完成在智能感知中建议完全相同..但我无法构建和运行结果。
    • @Mikk 尝试重新启动您的 PC 并重复手动输入,而不是复制 xmlns
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-15
    • 1970-01-01
    • 2017-05-16
    • 2010-12-13
    • 1970-01-01
    相关资源
    最近更新 更多