我正在学习自定义控件,并以 autoCompleteTextBox 为例。我正在为 WPF 项目(v 4.5 和 vb.net 4.5)创建自定义控件,它使用文本框基类。然后,我向控件添加了一个弹出窗口、列表框和按钮。我在列表框的数据模板的自定义控件中有一个依赖属性,但我无法将数据模板 pssed 到列表框。
这是数据模板的依赖属性:
#Region "DEPENDENCY PROPERTIES -- ItemTemplate"
Public Property ItemTemplate As DataTemplate
Get
Return GetValue(ItemTemplateProperty)
End Get
Set(ByVal value As DataTemplate)
SetValue(ItemTemplateProperty, value)
End Set
End Property
Public Shared ReadOnly ItemTemplateProperty As DependencyProperty = DependencyProperty.Register( _
"ItemTemplate", GetType(DataTemplate), GetType(AutoCompleteTextBox), _
New FrameworkPropertyMetadata(Nothing, FrameworkPropertyMetadataOptions.None, _
New PropertyChangedCallback(AddressOf OnItemTemplateChanged)))
Shared Sub OnItemTemplateChanged(d As DependencyObject, e As DependencyPropertyChangedEventArgs)
Dim actb As AutoCompleteTextBox = TryCast(d, AutoCompleteTextBox)
If actb IsNot Nothing Then
Dim TempTemplate As DataTemplate = TryCast(e.NewValue, DataTemplate)
If TempTemplate IsNot Nothing Then
actb.ItemTemplate = TempTemplate
End If
End If
End Sub
#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}}">
<Window.Resources>
<DataTemplate x:Key="CollectionTemplate">
<Border BorderBrush="Green" BorderThickness="2" CornerRadius="5" Padding="5,5,5,2">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Text="OBJECT: "/>
<TextBlock Grid.Column="1" Text="{Binding Name}"/>
<TextBlock Grid.Row="1" Text="{Binding id}"/>
<TextBlock Grid.Column="1" Grid.Row="1" Text="{Binding Job}"/>
</Grid>
</Border>
</DataTemplate>
</Window.Resources>
<Grid>
<krisis:AutoCompleteTextBox ItemsSource="{Binding Collection}"
ItemTemplate="{StaticResource CollectionTemplate}"
MaxmimumMatches="15"
MinimumFilterCharacters="1"
DisplayPath="Name"
Width="497" MinHeight="35" FontSize="18" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10,41,10,243" />
</Grid>
</Window>
我的问题:当我使用它来声明我的 itemtemplate 时,它没有被应用。列表框只显示列表框中每个对象的对象类型名称,而不是任何对象属性值。
有人可以帮我使用依赖属性来传递自定义控件内列表框的 DataTemplate。
提前致谢