【问题标题】:wpf dependency property error from custom control来自自定义控件的 wpf 依赖属性错误
【发布时间】:2025-11-22 14:55:02
【问题描述】:

我有一个依赖属性,它是基于文本框的自定义控件的一部分:在 wpf 4.5、vb.net 4.5、visual studio 2012 中。

这是属性声明:

#Region "DEPENDENCY PROPERTIES -- ItemsSource"
    Public Property ItemsSource As IEnumerable
        Get
            Return GetValue(ItemsSourceProperty)
        End Get
        Set(ByVal value As IEnumerable)
            SetValue(ItemsSourceProperty, value)
        End Set
    End Property
    Public ReadOnly ItemsSourceProperty As DependencyProperty = DependencyProperty.Register( _
                    "ItemsSource", GetType(DependencyObject), GetType(AutoCompleteTextBox), _
                    New FrameworkPropertyMetadata(Nothing, FrameworkPropertyMetadataOptions.None, _
                    New PropertyChangedCallback(AddressOf OnItemSourceChanged)))
#End Region

然后我在一个小示例项目中声明自定义控件以进行测试(自定义控件在同一灵魂的另一个项目中)

这是带有自定义控件的主窗口的 xaml:

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:krisis="clr-namespace:Krisis.Controls;assembly=Krisis.Controls"
    Title="MainWindow" Height="350" Width="525" x:Name="MyWindow"
    DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <Grid>
        <krisis:AutoCompleteTextBox ItemsSource="{Binding Collection, Mode=TwoWay}"  Width="497" MinHeight="35" FontSize="18" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10,41,10,243"/>
    </Grid>
</Window>

但是xaml编辑器在customcontrol行下划线并抛出如下错误:

错误 1 ​​无法在 'ItemsSource' 属性上设置 'Binding' 键入“自动完成文本框”。 “绑定”只能设置在 DependencyObject 的 DependencyProperty。

谁能帮我解决导致这个错误的原因,我不知道我的依赖属性声明在哪里出错。

【问题讨论】:

  • 贴出控件的完整代码。另外,为什么你的财产被声明为typeof(DependencyObject)?应该是typeof(IEnumerable)
  • @HighCore 你的权利,我正在玩弄试图让事情正常工作。

标签: .net wpf vb.net custom-controls dependency-properties


【解决方案1】:

DependencyProperty 必须是 Shared in VBStatic in C#

例子:

Public Property ItemsSource As IEnumerable
    Get
        Return GetValue(ItemsSourceProperty)
    End Get
    Set(ByVal value As IEnumerable)
        SetValue(ItemsSourceProperty, value)
    End Set
End Property

Public Shared ReadOnly ItemsSourceProperty As DependencyProperty = DependencyProperty.Register( _
                "ItemsSource", GetType(DependencyObject), GetType(AutoCompleteTextBox), _
                New FrameworkPropertyMetadata(Nothing, FrameworkPropertyMetadataOptions.None, _
                New PropertyChangedCallback(AddressOf OnItemSourceChanged)))

【讨论】:

  • 谢谢,已修复!这是我使用依赖属性的第一天。如果你不介意,为什么需要分享?
  • @J King,依赖属性用于绑定、动画等。它的定义是静态创建的,因为WPF运行时需要访问定义而不必多次实例化对象。之所以这样设计,是因为仅为获取依赖属性的定义而实例化不必要的对象会降低性能。