2013-04-15 84 views
1

我有一個依賴屬性是基於一個文本框自定義控制的一部分:在WPF 4.5,vb.net 4.5時,Visual Studio 2012從WPF自定義控件依賴屬性錯誤

這裏是財產申報:

#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 

我然後在用於測試的小樣本項目聲明定製控制(自定義控制是在相同的soultion另一個項目內)

下面是用於與自定義控制主窗口中的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線並引發了以下錯誤:

Error 1 A 'Binding' cannot be set on the 'ItemsSource' property of type 'AutoCompleteTextBox'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.

有人可以幫我解決是什麼原因造成這個錯誤,我無法揣摩出我的依賴屬性聲明錯誤。

+1

發佈控制的全碼。另外,爲什麼你的屬性聲明爲'typeof(DependencyObject)'?它應該是'typeof(IEnumerable)'。 –

+0

@HighCore你的權利,我一直在試圖讓事情發揮作用。 –

回答

1

DependencyProperty必須在VBStaticSharedC#

實施例:

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))) 
+0

哈哈很好。我沒有看到它=) –

+0

謝謝,修好了!這是我第一天使用依賴屬性。如果你不介意,爲什麼需要共享? –

+1

@J King,依賴屬性用於綁定,動畫等。它的定義被創建爲靜態的,因爲WPF運行時需要訪問定義而不必多次實例化對象。它是這樣設計的,因爲僅僅爲獲取依賴屬性的定義而實例化不必要的對象將會降低性能。 –