这个MSDN示例代码有什么作用? - ItemsControl.ItemTemplate
-
06-07-2019 - |
题
这是一个XAML代码示例,取自 MSDN库文章:
<ListBox Width="400" Margin="10" ItemsSource="{Binding Source={StaticResource myTodoList}}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=TaskName}" />
<TextBlock Text="{Binding Path=Description}"/>
<TextBlock Text="{Binding Path=Priority}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我正在寻找关于<StackPanel>
元素用法的解释。这个例子
- GT <!>;结果
这个面板将存在于ListBox中的哪个位置?
它在ItemTemplate中的用途是什么?
是否可以使用任何System.Windows.Controls.Panel,特别是Grid?
我如何使用<Grid>
元素作为ListBox中每个项目的模板?
这是我想要的概念:
http://img151.imageshack.us/img151/7960/graphconcept.png
我使用<Path>
元素绘制了图形,并且没有问题。
我正在研究轴的标签,我正在试验在ItemTemplate中使用<=>元素 - 但我不知道网格应该如何在这种情况下起作用,而且MSDN什么也没说关于他们的示例代码中的面板。
我的Y轴标签的XAML目前如下所示:
<ListBox Background="Transparent" BorderThickness="0" ItemsSource="{Binding Path=GraphLabelYData}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="{Binding Path=GraphLabelSpacing}" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="{Binding ElementName=GraphLabelYData, Path=GraphLabelMarkerLength}" />
</Grid.ColumnDefinitions>
<TextBlock HorizontalAlignment="Right" VerticalAlignment="Bottom" Text="{Binding Path=GraphLabelTag}" />
<Rectangle Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" Stroke="Black" Fill="Black" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
这看起来是否正确?在运行时没有显示任何内容,但我想在开始调试数据绑定和代码隐藏之前确保正确建模XAML。
解决方案
<!>“这个面板将在ListBox中存在于哪里?<!>”; - 列表框将为每个列表项创建一个副本,即myTodoList集合中每个元素的一个副本。因此,在每个列表项中,您将三个标签堆叠在一起。
<!>“;它在ItemTemplate中的用途是什么?<!>”; - 为了能够为ItemsSource中的每个元素显示多个控件。与WPF中的许多内容一样,ItemTemplate只能占用一个子元素,因此如果您需要多个子元素,则需要指定它们的布局方式,并通过添加面板(在本例中为StackPanel)来实现。
<!>“可以使用任何System.Windows.Controls.Panel吗,特别是Grid?<!>; - 你打赌。
<!>“我如何使用<Grid>
元素作为ListBox中每个项目的模板?<!> quot; - 就像在其他任何地方使用网格一样。没有什么不同;只是ItemsControl(及其后代,ListBox)将创建Grid的多个实例。但请注意,在ItemTemplate中,您的DataContext将是当前列表项,因此您的{Binding}
s将相对于该列表项(除非您使用例如ElementName指定)。
<!>“这看起来是否正确?<!> quot; - 这应该作为一个单独的问题发布,因为它与MSDN示例的问题无关,我甚至不确定你要做什么。但我会尝试回答:我怀疑有问题,因为你使用的名称是<!>“GraphLabelYData <!>”;两种不同的方式。在ColumnDefinition中,据我所知,您将GraphLabelYData视为XAML元素的名称(即您正在使用Name="GraphLabelYData"
或x:Name="GraphLabelYData"
在窗口/ page / UserControl中查找另一个控件,并且正在阅读那个控件的GraphLabelMarkerLength属性);但是在TextBlock中,您将GraphLabelYData视为当前集合项上属性的名称。我怀疑其中一个是不对的。