我只是试图理解 ItemsPanelTemplate 的概念。为此,我构建了一个小样本解决方案。
我有一个带有以下代码的用户控件“MyListView”。
MyListView.xaml:
<UserControl x:Class="WpfApplication2.MyListView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<Style TargetType="ListViewItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListViewItem">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Border BorderBrush="Black" BorderThickness="1" Margin="0" Padding="0" Width="100" Background="Gray">
<TextBlock Text="Text" HorizontalAlignment="Center" />
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<ListView ItemsSource="{Binding Path=TreeItemChildren}">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch">
</StackPanel>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
</ListView>
</UserControl>
在 MyListView.cs 我添加了一个 DependencyProperty 来将数据绑定到应该显示的数据:
public partial class MyListView : UserControl
{
public MyListView()
{
this.TreeItemChildren = new ObservableCollection<string>();
this.TreeItemChildren.Add("Text0");
this.TreeItemChildren.Add("Text1");
this.TreeItemChildren.Add("Text2");
InitializeComponent();
}
public ObservableCollection<string> TreeItemChildren
{
get { return (ObservableCollection<string>)GetValue(TreeItemChildrenProperty); }
set { SetValue(TreeItemChildrenProperty, value); }
}
// Using a DependencyProperty as the backing store for TreeItemChildren. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TreeItemChildrenProperty =
DependencyProperty.Register("TreeItemChildren", typeof(ObservableCollection<string>), typeof(MainWindow), new UIPropertyMetadata(null));
}
当我现在尝试在我的 MainWindow 中使用此 UserControl 时,没有要显示的数据。这是什么原因?