【问题标题】:WPF CustomControl can't inherit from TextBlock controlWPF CustomControl 不能从 TextBlock 控件继承
【发布时间】:2016-05-09 11:54:20
【问题描述】:

我正在制作一个带有 CustomControls 的 WPF CustomControlLibrary,它继承自 Label、TextBox 等标准控件。 当我尝试制作另一个继承自 TextBlock 的 CustomControl 时,我得到了奇怪的错误。 似乎是 CustomControl 不能从 TextBlock 继承。

但是为什么呢?

提前致谢!

【问题讨论】:

  • 有关“奇怪错误”的任何详细信息可能会有所帮助吗?
  • 在我的情况下,继承自 TextBlock 的 CustomControl 无法再注册,并且对于库项目和引用库的 WPF 项目都不知道。

标签: wpf


【解决方案1】:

我刚刚创建了继承自 TextBlock 的自定义控件:

using System.Windows.Controls;
namespace WpfApplication1
{
    public class CustomTextBlock : TextBlock
    {
    }
}

并在同一个项目中使用它:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1">
    <Grid>
        <local:CustomTextBlock Text="Hello" />
    </Grid>        
</Window>

所以分析器是:

你可以从 TextBlock 继承

但是,为了在 xaml 中使用它,您必须先编译项目。您的代码中可能还有其他错误会阻止项目编译,因此您可能还会遇到类似

的错误

The type 'local:CustomTextBlock' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built

或类似的错误:

The name "CustomTextBlock" does not exist in the namespace "clr-namespace:WpfApplication1".

一旦您修复了其他错误,这些错误也会消失。

【讨论】:

  • 我试过了,但现在我在 Generic.xaml 中收到另一条错误消息:在“CustomTextBlock”类型中找不到样式属性“模板”。
  • 这是因为TextBlock没有模板。您不能为没有模板的控件指定模板。您可能正在寻找 ContentControl,而不是 TextBlock。如果您只想更改外观并且不需要指定任何额外的属性,那么您根本不需要自定义控件。您只需要为 ContentControl 或 Label 创建单独的样式
  • 好的 Liero,在你回答之后我也是这么想的。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2020-06-10
  • 1970-01-01
  • 2021-10-30
  • 2023-03-10
  • 1970-01-01
  • 2014-12-03
  • 2021-05-06
  • 1970-01-01
相关资源
最近更新 更多