2012-01-13 79 views
0

我只是尝试了解ItemsPanelTemplate的概念。为此,我构建了一个小样本解决方案。元素不显示与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,没有要显示的数据。这是什么原因?

回答

0

您没有bound任何ListBoxItem属性在控制模板中,Content不会显示出于该原因。

<TextBlock Text="Text" HorizontalAlignment="Center" /> 

有:

一般你会替换此

<ContentPresenter HorizontalAlignment="Center"/> 

(如果模板控件是一个ContentControlContentPresenter结合自动Content相关属性)

另外, ListView.ItemsSource绑定到DataContext(未设置)和不应该设置为,因为它会干扰控件实例上的绑定),将其更改为某种程度上将目标设置为UserControl(例如,使用ElementNameRelativeSource)。

(应该有绑定错误引起的ItemsSource绑定,学习how to debug them