WPF自定义带边框按钮类与资源字典关联报错求助
解决WPF自定义按钮的XDG0008和XDG0012错误
一、修复XDG0008:命名空间中不存在CustomButtonWithBorder
这个错误大多是资源字典的命名空间引用与自定义类的实际命名空间不匹配,或者类定义存在问题,按以下步骤排查:
- 检查自定义类的命名空间与继承
确保CustomButtonWithBorder正确继承Button,且命名空间与项目一致,示例代码:
using System.Windows; using System.Windows.Controls; namespace YourProjectNamespace // 替换成你的项目实际命名空间 { public class CustomButtonWithBorder : Button { // 后续添加依赖属性 } }
- 修正资源字典的命名空间引用
在ResourceDictionary根节点添加正确的xmlns引用,clr-namespace要和类的命名空间一致,assembly为你的项目程序集名称(通常和项目名相同):
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:YourProjectNamespace;assembly=YourProjectAssembly"> <!-- 按钮样式定义 --> </ResourceDictionary>
- 确保类被正确编译
刚创建类后先编译一次项目,让XAML编辑器能识别到该类。
二、修复XDG0012:未识别NormalBackgroundColor元素
这个错误是因为CustomButtonWithBorder类中未定义名为NormalBackgroundColor的依赖属性,或属性名称拼写错误,需添加对应依赖属性:
- 添加NormalBackgroundColor依赖属性
在CustomButtonWithBorder类中添加如下代码,确保属性名称与XAML中引用完全一致:
using System.Windows.Media; public static readonly DependencyProperty NormalBackgroundColorProperty = DependencyProperty.Register( "NormalBackgroundColor", typeof(Brush), typeof(CustomButtonWithBorder), new PropertyMetadata(Brushes.LightGray)); // 默认值可自行修改 public Brush NormalBackgroundColor { get { return (Brush)GetValue(NormalBackgroundColorProperty); } set { SetValue(NormalBackgroundColorProperty, value); } }
- 在资源字典中正确绑定属性
按钮样式里使用该属性时,通过TemplateBinding绑定到自定义按钮的属性:
<Style TargetType="{x:Type local:CustomButtonWithBorder}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:CustomButtonWithBorder}"> <Border CornerRadius="8" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding NormalBackgroundColor}"> <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style>
验证步骤
- 编译整个项目,确保无编译错误。
- 在视图中使用自定义按钮,动态设置属性确认样式生效:
<local:CustomButtonWithBorder Content="测试按钮" BorderBrush="Blue" BorderThickness="2" NormalBackgroundColor="LightBlue"/>
内容的提问来源于stack exchange,提问作者Dustin Derr
相关产品推荐
相关产品推荐

