WPF - ItemTemplate未按预期运行

Eig*_*ite 4 wpf user-controls datatemplate itemtemplate itemspanel

我有一个UserControl我用来显示UIElements 的列表.控件包含一个单独的ItemsControl,它被ItemPanelTemplate切换为一个水平StackPanel,它被ItemsSource绑定到一个DependencyProperty暴露的UserControl和它的ItemTemplate设置UserControl.Resources.

一切都很好,除了ItemTemplate永远不会得到应用,我不明白为什么.完整的来源如下.

UserControl.xaml -

<UserControl x:Name="UC" x:FieldModifier="private" x:Class="ContentSliderControl.ContentSlider"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<UserControl.Resources>

    <DataTemplate x:Key="pageTemplate">
        <Border CornerRadius="10" Padding="5" Height="200" Width="200" Background="#333">
            <ContentControl Content="{Binding}"/>
        </Border>
    </DataTemplate>

    <ItemsPanelTemplate x:Key="template">
        <StackPanel IsItemsHost="True"
            Orientation="Horizontal"
            ScrollViewer.HorizontalScrollBarVisibility="Disabled"
            ScrollViewer.VerticalScrollBarVisibility="Disabled"/>
    </ItemsPanelTemplate>
</UserControl.Resources>

<ItemsControl ItemsPanel="{StaticResource template}" 
              ItemTemplate="{StaticResource pageTemplate}" 
              ItemsSource="{Binding ElementName=UC,Path=Pages}"/>
Run Code Online (Sandbox Code Playgroud)

UserControl.xaml.cs -

[ContentProperty("Pages")]
public partial class ContentSlider : UserControl
{


    public List<UIElement> Pages
    {
        get { return (List<UIElement>)GetValue(PagesProperty); }
        //set { SetValue(PagesProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Pages.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty PagesProperty =
        DependencyProperty.Register("Pages", typeof(List<UIElement>), typeof(ContentSlider), new UIPropertyMetadata(null));



    public ContentSlider()
    {
        InitializeComponent();
    }
}
Run Code Online (Sandbox Code Playgroud)

}

我在主窗口中使用控件,如下所示 -

    <slider:ContentSlider >
    <slider:ContentSlider.Pages>
        <Button>1</Button>
        <Button>2</Button>
        <Button>3</Button>
        <Button>4</Button>
    </slider:ContentSlider.Pages>
</slider:ContentSlider>
Run Code Online (Sandbox Code Playgroud)

按钮看起来很好但不在200px方形边框内.

任何帮助都会非常有用.谢谢.

Rob*_*nee 6

Nir是正确的,如果他们是UIElements ,ItemsControl将直接添加项目Panel.我在MSDN中找不到这种行为,但是WPF博士在他关于项目容器的文章中提到了这一点:

如果将UIElement添加到显式ItemsControl实例的Items集合中(而不是像ListBox这样的派生类的实例),它将成为items面板的直接子节点.如果添加了非UIElement,它将被包装在ContentPresenter中.

您的解决方案可能是使用一个ListBox替代,并成立ItemContainerStyle一个新StyleListBoxItem,并且在风格,使用ControlTemplateBorder它.