只能在 DependencyObject 的 DependencyProperty 上设置“绑定" [英] A 'Binding' can only be set on a DependencyProperty of a DependencyObject
问题描述
从一个基于TextBox
的自定义控件,我创建了一个名为Items
的属性,这样:
From a custom control based on TextBox
, I created a property named Items
, in this way:
public class NewTextBox : TextBox
{
public ItemCollection Items { get; set; }
}
在 XAML 中使用自定义控件时,我无法绑定属性,因为它引发异常只能在 DependencyObject 的 DependencyProperty 上设置绑定".
When using the custom control in XAML, I cannot bind the property because it raises exception "A 'Binding' can only be set on a DependencyProperty of a DependencyObject.".
如何解决这个异常?
推荐答案
作为旁注,另外值得注意的是,如果您在对象之间进行复制和粘贴而忘记更改第二个 ,则会出现这些绑定错误typeof(Object)
语句.
As a side note, it is also worth noting that you will get these binding errors if you copy and paste between objects and forget to change the second typeof(Object)
statement.
我一小时想不通为什么会出现此错误,因为一切似乎都已定义且正确.我已经将我的属性移动到用户控件中,因为我想从单个集合转到一个列表.因此:
I couldn't figure out for a good hour why I was getting this error as everything appeared to be defined and correct. I'd moved my properties into a usercontrol as I wanted to go from a single set to a list. Thus:
public static readonly DependencyProperty FoldersProperty = DependencyProperty
.Register("Folders", typeof(OutlookFolders), typeof(MainWindow),
new FrameworkPropertyMetadata(new OutlookFolders()));
public OutlookFolders Folders
{
get { return GetValue(FoldersProperty) as OutlookFolders; }
set { SetValue(FoldersProperty, value); }
}
应该变成:
public static readonly DependencyProperty FoldersProperty = DependencyProperty
.Register("Folders", typeof(OutlookFolders), typeof(SavedFolderControl),
new FrameworkPropertyMetadata(new OutlookFolders()));
public OutlookFolders Folders
{
get { return GetValue(FoldersProperty) as OutlookFolders; }
set { SetValue(FoldersProperty, value); }
}
在我进行此更改之前,我一直收到错误消息:无法在SavedFolderControl"类型的属性文件夹"上设置绑定".只能在 DependencyObject 的 DependencyProperty 上设置绑定".
Until I did this change I kept receiving the error:
A 'Binding' cannot be set on the property 'Folders' of type 'SavedFolderControl'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.
这篇关于只能在 DependencyObject 的 DependencyProperty 上设置“绑定"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!