我在WPF中有一个用户控件,它具有与依赖项属性的绑定。当我尝试编译应用程序时,我得到一个“属性名称”已经被“ControlName”错误注册,并且设计者显示“无法创建”用户控件“错误的实例。
以下是我的简单控件:
ExampleUserControl.xaml:
<UserControl x:Class="ExampleApp1.ExampleUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:ExampleApp1"
mc:Ignorable="d" >
<TextBox Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:ExampleUserControl}}, Path=SomeStringValue}" />
</UserControl>
ExampleUserControl.xaml.cs:
public partial class ExampleUserControl : UserControl
{
public DependencyProperty SomeStringValueProperty = DependencyProperty.Register("SomeStringValue", typeof(string), typeof(ExampleUserControl));
public string SomeStringValue
{
get
{
return GetValue(SomeStringValueProperty) as string;
}
set
{
SetValue(SomeStringValueProperty, value);
}
}
public ExampleUserControl()
{
InitializeComponent();
}
}
它托管的主窗口:
<Window x:Class="ExampleApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ExampleApp1"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<local:ExampleUserControl SomeStringValue="Test 1" />
<local:ExampleUserControl SomeStringValue="Test 2" />
</StackPanel>
</Window>
以下是设计师的样子:
以下是XAML设计师的样子:
答案 0 :(得分:23)
发生的事情是Dependency Property在同一名称和所有者下多次注册。依赖属性旨在拥有单个所有者,并且应该静态实例化。如果您没有静态实例化它们,则会尝试为每个控件实例注册它们。
使您的DependencyProperty声明为静态。 将其改为:
public DependencyProperty SomeStringValueProperty = DependencyProperty.Register("SomeStringValue", typeof(string), typeof(ExampleUserControl));
要强>
public static DependencyProperty SomeStringValueProperty = DependencyProperty.Register("SomeStringValue", typeof(string), typeof(ExampleUserControl));
答案 1 :(得分:5)
此类型的错误消息是通过向基类
注册依赖项属性引起的即这个
public static readonly DependencyProperty WorkerStateProperty =
DependencyProperty.Register("WorkerState", typeof(State), typeof(Control),
new FrameworkPropertyMetadata(State.Stopped, new PropertyChangedCallback(OnWorkerStateChanged)));
而不是
public static readonly DependencyProperty WorkerStateProperty =
DependencyProperty.Register("WorkerState", typeof(State), typeof(WorkerControl),
new FrameworkPropertyMetadata(State.Stopped, new PropertyChangedCallback(OnWorkerStateChanged)));
我的WorkerControl类派生自Control
答案 2 :(得分:0)
我对两个控件之间的依赖项属性进行了剪切和粘贴,却忘记了将已注册的类从第一个控件更改为第二个控件。因此重复。
public static readonly DependencyProperty CurrentBatchProperty =
DependencyProperty.Register(
"CurrentBatch",
typeof(Batch),
typeof({--- Must be same as encompassing class --}), // Error if not set properly.
new PropertyMetadata(null, OnCurrentBatchPropertyChanged));
对于粘贴代码,我的原始控件是 then ,将其注册到两个不同的控件中,并得到了弯弯曲曲的一行(在放置页面上)和错误。