WPF:自定义控件属性已被另一个自定义控件错误注册

标签 wpf xaml wpf-controls

我创建了两个完全相同的自定义控件,只是它们属于两种不同的类型。

ControlOne

public class ControlOne : TextEdit
    {
        public static readonly DependencyProperty AwesomeSauceProperty =
         DependencyProperty.Register("AwesomeSauce", typeof(string), typeof(FormTextEditInput));           

        public string AwesomeSauce
        {
            get { return GetValue(AwesomeSauceProperty) as string; }
            set { SetValue(AwesomeSauceProperty, value); }
        }

    }

ControlTwo
public class ControlTwo : PasswordEdit
        {
            public static readonly DependencyProperty AwesomeSauceProperty =
             DependencyProperty.Register("AwesomeSauce", typeof(string), typeof(FormTextEditInput));           

            public string AwesomeSauce
            {
                get { return GetValue(AwesomeSauceProperty) as string; }
                set { SetValue(AwesomeSauceProperty, value); }
            }

        }

在XAML中,我只是这样做
<controls:ControlOne AwesomeSauce="Yummy"/>
<controls:ControlTwo AwesomeSauce="Tummy"/>

我得到错误
System.ArgumentException
'AwesomeSauce' property was already registered by 'ControlOne'.

您可能会问为什么我需要两个执行相同功能的控件,所以我只能创建数据模板并继续前进。但是我想变得固执,说我需要执行相同操作的不同类型的自定义控件。如果可以使用通用类型的自定义控件,那就很好了,但是我发现那是不可能的(对吗?)。

我也不想使用其他名称,因为那只是解决问题的方法。

我只希望我的两个控件能够为它们的依赖项属性使用相同的名称。这里有我想念的东西吗?还是我只是完全不允许使用相同的名称?

我猜想附加属性将是解决方案,但是我真的很想插入自定义控件。

最佳答案

ownerType方法的第三个参数DependencyProperty.Register必须是注册属性的类的类型,即您的情况下的ControlOne和ControlTwo:

public class ControlOne : TextEdit
{
    public static readonly DependencyProperty AwesomeSauceProperty =
        DependencyProperty.Register("AwesomeSauce", typeof(string), typeof(ControlOne));
    ...
}

public class ControlTwo : TextEdit
{
    public static readonly DependencyProperty AwesomeSauceProperty =
        DependencyProperty.Register("AwesomeSauce", typeof(string), typeof(ControlTwo));
    ...
}

关于WPF:自定义控件属性已被另一个自定义控件错误注册,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36503442/

相关文章:

image - 如何更改 View 中图像的前景色

wpf - 单击/触摸 PART_Textbox 时切换日期选择器日历

c# - 如何将数据表绑定(bind)到 wpf 可编辑组合框 : selectedItem showing System. Data.DataRowView

WPF 事件触发器 - 无法将属性 'MouseEnter' 中的字符串 'RoutedEvent' 转换为 'System.Windows.RoutedEvent' 类型的对象

c# - 在 C# 中实现脚本语言

c# - 如何使用 Helix Toolkit 在 WPF 中导入 3D 模型?

c# - 在 WPF 的代码隐藏中为 ListBox 创建 ItemTemplate - 第 II 部分

c# - ContentControl 在通过 UI 自动化测试启动应用程序时不可见,但在用户启动应用程序时可见

c# - 如何为相同类型的 UIElement 编写通用事件处理程序?

c# - 附加事件?如何在运行时删除 WPF DataGrid 的 ScrollChanged 事件处理程序