我创建了两个完全相同的自定义控件,只是它们属于两种不同的类型。
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/