我正在开发一个源自 ListBox 的自定义控件。作为我的控制的一部分,我想提供一个默认的 ItemTemplateSelector。不幸的是,我无法让它找到我的 DataTemplateSelector。这是代码,省略了不相关的细节:
public class AnnotationTemplateSelector : DataTemplateSelector
{
public DataTemplate BoxValuePairTemplate { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
return BoxValuePairTemplate;
}
}
和 Xaml...
<DataTemplate x:Key="BoxValuePairDataTemplate">
<Grid TextBlock.FontSize="9" Height="13" Width="{Binding Path=Width}" SnapsToDevicePixels="False">
... etc...
</Grid>
</DataTemplate>
选择器:
<Annotations:AnnotationTemplateSelector BoxValuePairTemplate="{StaticResource BoxValuePairDataTemplate}"
x:Key="AnnotationTemplateSelector" />
样式:
<Style TargetType="{x:Type Annotations:BoxEditorSurface}">
<Setter Property="IsTabStop" Value="False"/>
<Setter Property="ItemTemplateSelector" Value="{StaticResource AnnotationTemplateSelector}"/>
... etc ...
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Canvas.Left" Value="{Binding Path=X, Mode=TwoWay}" />
<Setter Property="Canvas.Top" Value="{Binding Path=Y, Mode=TwoWay}" />
<Setter Property="Padding" Value="0" />
<Setter Property="IsTabStop" Value="False" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<ContentPresenter x:Name="contentPresenter"
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
Margin="{TemplateBinding Padding}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter Property="IsSelected" Value="True" />
</Trigger>
</Style.Triggers>
</Style>
</Setter.Value>
</Setter>
</Style>
不幸的是,应用模板后,ItemTemplateSelector 始终为空,并且没有显示绑定错误。
想法?