我正在尝试基于 a 创建自定义模板化控件,ListBox以仅显示控件集合中的单个选定项。为此,我定义了一个模板,其ContentPresenter数据绑定到SelectedItem控件的属性。如场景 1 所示,在为控件提供UIElement.
但是当需要使用 aDataTemplate来显示实体对象时,会ItemTemplate被忽略,因为控件有 aTemplate会阻止使用 `ItemTemplate。从我读过的内容来看,这是设计使然,而且有点道理。
但是我怎样才能使用DataTemplates我的控件ItemTemplate并保留我的控件默认模板呢?
我尝试过覆盖PrepareContainerForItemOverride,许多不同的模板配置都无济于事。
这是我尝试的一些方法:
<UserControl.Resources>
    <local:StringCollection x:Key="MyColors">
        <sys:String>Yellow</sys:String>
        <sys:String>Purple</sys:String>
    </local:StringCollection>
</UserControl.Resources>
<StackPanel Background="White">
    <TextBlock Margin="0,25,0,0">Scenario 1: Providing UIElements to the
        ControlTemplate's ContentPresenter: Works</TextBlock>
    <control:RotatingFlipView x:Name="Works" SelectedIndex="1">
        <control:RotatingFlipView.Template>
            <ControlTemplate>
                <ContentPresenter
                     Content="{Binding ElementName=Works, Path=SelectedItem}"/>
            </ControlTemplate>
        </control:RotatingFlipView.Template>
        <Rectangle Height="100" Width="100" Fill="Red"/>
        <Rectangle Height="100" Width="100" Fill="Blue"/>
        <Rectangle Height="100" Width="100" Fill="Green"/>
    </control:RotatingFlipView>
    <TextBlock Margin="0,25,0,0">Scenario 2: The ItemTemplate provided is ignored in
        favor of the RotatingFlipView's Template which displays the source as raw
        Strings</TextBlock>
    <control:RotatingFlipView x:Name="Broken"
                              ItemsSource="{StaticResource MyColors}">
        <control:RotatingFlipView.Template>
            <ControlTemplate>
                <ContentPresenter
                    Content="{Binding ElementName=Broken, Path=SelectedItem}"/>
            </ControlTemplate>
        </control:RotatingFlipView.Template>
        <control:RotatingFlipView.ItemTemplate>
            <DataTemplate>
                <Rectangle Height="100" Width="100" Fill="{Binding}"/>
            </DataTemplate>
        </control:RotatingFlipView.ItemTemplate>
    </control:RotatingFlipView>
    <TextBlock Margin="0,25,0,0">Scenario 3: Removing the RotatingFlipView's
        Template, causes the display to fall back on the ListBox's Template,
        though now my ItemTemplate is used:</TextBlock>
    <control:RotatingFlipView x:Name="Broken2"
                              ItemsSource="{StaticResource MyColors}">
        <control:RotatingFlipView.ItemTemplate>
            <DataTemplate>
                <Rectangle Height="100" Width="100" Fill="{Binding}"/>
            </DataTemplate>
        </control:RotatingFlipView.ItemTemplate>
    </control:RotatingFlipView>
</StackPanel>
旋转翻转视图.cs
public class RotatingFlipView : ListBox
{
    public RotatingFlipView()
    {
        DefaultStyleKey = typeof(RotatingFlipView);
    }
}
通用的.xaml
<Style TargetType="local:RotatingFlipView">
    <Setter Property="SelectionMode" Value="Single"/>
    <Setter Property="SelectedIndex" Value="0"/>
</Style>
输出:
