【发布时间】: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