如何在 WPF ResouceDictionary 文件中添加自定义 UI 控制器作为目标类型

How to add a custom UI Controller as the targettype in WPF ResouceDictionary File

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
   <Style x:Key=CustomDataGrid" TargetType="{x:Type CusGrid}">
      <Setter Property="Background" Value="{StaticResource Red.Background}" />
   </Style>
</ResourceDictionary>

我已经创建了一个具有附加功能的自定义数据网格,我打算使用此资源字典文件对其进行样式设置。但是当我输入 TargetType="{x:Type CusGrid}" 时它会出错。我该如何解决这个问题?

您需要将 命名空间前缀 添加到 XAML 中的根元素。

您的问题并未指明您的自定义控件位于哪个 C# 命名空间中,因此我将仅使用 XYZ 作为占位符。像这样向 ResourceDictionary 元素添加一个新属性:

<ResourceDictionary ... xmlns:mycontrols="clr-namespace:XYZ">

XYZ 替换为 CusGrid 控件所在的实际命名空间。

接下来,将您的 TargetType 更改为:

... TargetType="{x:Type mycontrols:CusGrid}">

看看 mycontrols 命名空间前缀是如何用在 CusGrid 类型名称前面的。

您可以将 mycontrols 更改为您想要的任何内容,只要您不使用已经引用的前缀(因此您不能使用 x 作为前缀)。