【发布时间】:2012-07-24 10:32:57
【问题描述】:
我有一个创建对象列表的简单类:
namespace TestWPF2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public ObservableCollection<TestObj> SomeList { get; set; }
public string WindowTitle { get; set; }
public MainWindow()
{
this.DataContext = this;
WindowTitle = "People";
SomeList = new ObservableCollection<TestObj>();
SomeList.Add(new TestObj("Bob"));
SomeList.Add(new TestObj("Jane"));
SomeList.Add(new TestObj("Mike"));
InitializeComponent();
}
}
}
TestObj类如下:
namespace TestWPF2
{
public class TestObj
{
public string FirstName { get; set; }
public TestObj(string firstName)
{
this.FirstName = firstName;
}
}
}
然后我尝试使用以下内容显示列表中的每个项目:
<Window x:Class="TestWPF2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestWPF2"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate DataType="{x:Type local:TestObj}">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Pos: "/>
<TextBlock x:Name="posText"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Name: "/>
<TextBlock Text="{Binding FirstName}"/>
</StackPanel>
</StackPanel>
<!-- THESE TRIGGERS DONT WORK -->
<DataTemplate.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Text" Value="First" TargetName="posText"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Text" Value="Second" TargetName="posText"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="3">
<Setter Property="Text" Value="Third" TargetName="posText"/>
</Trigger>
</DataTemplate.Triggers>
</DataTemplate>
</Window.Resources>
<StackPanel>
<TextBlock Text="{Binding Title}"/>
<ItemsControl HorizontalAlignment="Stretch"
ItemsSource="{Binding SomeList}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</StackPanel>
</Window>
我想显示的是这样的:
Pos: First
Name: Bob
Pos: Second
Name: Jane
etc.
绑定到列表中每个项目的 FirstName 属性非常简单,但我也想绑定到列表中的 index。我知道我可以使用 ItemsControl.AlternationIndex 从 ItemsControl 内部执行此操作,但是如何从 DataTemplate 内部链接到 AlternationIndex?
【问题讨论】:
-
您考虑过RelativeSource 绑定吗?它不是最好的方法,但我在这种情况下工作。另请记住,AlternationIndex 不是列表中的索引,而是更像是当前索引的模数。例如,您可以使用它为网格中的每一行着色。
-
嗨,对不起,以上是我的代码的精简版。我将 ItemsControl 上的 AlternationCount 属性设置为一个适当高的数字,这样它就不会“换行”。我尝试过使用 RelativeSource,但到目前为止没有运气!
标签: c# .net wpf datatemplate itemscontrol