1

我有一个依赖属性,它是基于文本框的自定义控件的一部分:在 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 ​​无法在“AutoCompleteTextBox”类型的“ItemsSource”属性上设置“绑定”。只能在 DependencyObject 的 DependencyProperty 上设置“绑定”。

有人可以帮我解决导致此错误的原因吗,我无法弄清楚我的依赖属性声明在哪里出错。

4

1 回答 1

2

DependencyProperty必须SharedVBStatic在_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)))
于 2013-04-15T21:04:44.200 回答