WPF - ItemTemplate 未按预期运行 [英] WPF - ItemTemplate not acting as expected
问题描述
我有一个 UserControl
用于显示 UIElement
的列表.该控件由单个 ItemsControl
组成,它的 ItemPanelTemplate
切换为水平 StackPanel
,其 ItemsSource
绑定到 <UserControl
公开的code>DependencyProperty 及其在UserControl.Resources
中设置的ItemTemplate
.
I have a UserControl
which I'm using to display a list of UIElement
s. The control consists of a single ItemsControl
with it's ItemPanelTemplate
switched for a horizontal StackPanel
, its ItemsSource
bound to a DependencyProperty
exposed by the UserControl
and its ItemTemplate
set in the UserControl.Resources
.
一切正常,除了 ItemTemplate
从未得到应用,我不明白为什么.完整来源如下.
Everything works fine except the ItemTemplate
never get's applied and I can't see why. The full source is below.
UserControl.xaml -
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}"/>
UserControl.xaml.cs -
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();
}
}
}
我像这样在主窗口中使用控件 -
I consume the control in my main window like this -
<slider:ContentSlider >
<slider:ContentSlider.Pages>
<Button>1</Button>
<Button>2</Button>
<Button>3</Button>
<Button>4</Button>
</slider:ContentSlider.Pages>
</slider:ContentSlider>
按钮看起来不错,但不在 200px 方形边框内.
The buttons appear fine but not inside the 200px square border.
任何帮助将不胜感激.谢谢.
Any help would be greatlly appriciated. Thanks.
推荐答案
因为是UIElement的列表,只有在item不能直接显示的情况下才会应用item模板.
It's because it's a list of UIElement, the item template is only applied if the items can't be displayed directly.
这篇关于WPF - ItemTemplate 未按预期运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!