我在 WPF 中创建了这个用户控件
<UserControl x:Class="WpfApp1.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<UserControl.Template>
<ControlTemplate TargetType="{x:Type local:UserControl1}">
<Grid x:Name="LayoutRoot" Background="White" Margin="7,7,7,0">
</Grid>
</ControlTemplate>
</UserControl.Template>
Run Code Online (Sandbox Code Playgroud)
当我编译这个时,我收到以下错误。
“UserControl1”ControlTemplate TargetType 与模板化类型“UserControl”不匹配。
但当我调试应用程序时,它工作正常。
这个错误是什么意思?我该如何解决它?
该错误很可能仅在打开 XAML 编辑器时才会出现,对吗?这是因为这是 XAML 设计器问题,而不是 WPF 或 .NET 问题。这就是为什么它在运行时工作正常,但在 Visual Studio 中显示错误。
我遇到类似的问题,因为 XAML 设计器也不支持 ControlTemplates 上的多态性(模板的 TargetType="baseclass",但应用于派生类) - 但这在运行时也有效。
主要解决方法是不使用 XAML 定义自定义控件。相反,创建一个模板化控件,其中模板由外部样式资源选择。有关详细信息,请参阅http://mrbool.com/how-to-create-a-custom-control-in-xaml-and-c/26447 。