WPF,两个自定义控件不能创建同名的依赖项属性吗?该如何解决
WPF,两个自定义控件不能创建同名的依赖项属性吗?
有一个自定义控件CustomControl1:
XAML部分就不写了,因为没有什么特殊的。
下面是后台部分:
CustomControl1自定义控件继承自Control,创建了一个依赖项属性Value。
现在创建第二个自定义控件CustomControl2,代码与CustomControl1一模一样,也是创建了一个同名的依赖项属性Value。
在主窗体中使用这两个控件:
现在报错了,说:“Value”属性已经由“CustomControl1”注册。请问,不同的控件难道不能创建相同名称的依赖项属性吗?

------解决方案--------------------
“代码与CustomControl1一模一样”?
难道你在 CustomControl2 中也是写的 .....typeof(string), typeof(CustomControl1), new .......?
有一个自定义控件CustomControl1:
XAML部分就不写了,因为没有什么特殊的。
下面是后台部分:
public class CustomControl1 : Control
{
static CustomControl1()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1)));
}
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(string), typeof(CustomControl1), new PropertyMetadata("张三", new PropertyChangedCallback(Valuechanged)));
public string Value
{
get { return (string)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public static void Valuechanged(DependencyObject d, DependencyPropertyChangedEventArgs e) //变更通知
{
}
}
CustomControl1自定义控件继承自Control,创建了一个依赖项属性Value。
现在创建第二个自定义控件CustomControl2,代码与CustomControl1一模一样,也是创建了一个同名的依赖项属性Value。
在主窗体中使用这两个控件:
<Window x:Class="WPF3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPF3"
Title="MainWindow" Height="350" Width="525">
<Grid>
<local:CustomControl1/>
<local:CustomControl2/>
</Grid>
</Window>
现在报错了,说:“Value”属性已经由“CustomControl1”注册。请问,不同的控件难道不能创建相同名称的依赖项属性吗?
------解决方案--------------------
“代码与CustomControl1一模一样”?
难道你在 CustomControl2 中也是写的 .....typeof(string), typeof(CustomControl1), new .......?