此解决方案会影响最后一行并随着基础集合的更改而更新:
代码隐藏
转换器需要 3 个参数才能正常工作 - 当前项、itemscontrol、itemscount,如果当前项也是最后一项,则返回 true:
class LastItemConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
int count = (int)values[2];
if (values != null && values.Length == 3 && count>0)
{
System.Windows.Controls.ItemsControl itemsControl = values[0] as System.Windows.Controls.ItemsControl;
var itemContext = (values[1] as System.Windows.Controls.ContentPresenter).DataContext;
var lastItem = itemsControl.Items[count-1];
return Equals(lastItem, itemContext);
}
return DependencyProperty.UnsetValue;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
XAML
DataTemplate 的数据触发器,包括一个名为“PART_TextBox”的文本框:
<DataTemplate.Triggers>
<DataTrigger Value="True" >
<DataTrigger.Binding>
<MultiBinding Converter="{StaticResource LastItemConverter}">
<Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}" />
<Binding RelativeSource="{RelativeSource Self}"/>
<Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}" Path="Items.Count"/>
</MultiBinding>
</DataTrigger.Binding>
<Setter Property="Foreground" TargetName="PART_TextBox" Value="Red" />
</DataTrigger>
</DataTemplate.Triggers>
转换器作为 Xaml 中的静态资源
<Window.Resources>
<local:LastItemConverter x:Key="LastItemConverter" />
</Window.Resources>
快照
以及它在行动中的快照
代码已经从这个'codeproject'添加到itemscontrol
https://www.codeproject.com/Articles/242628/A-Simple-Cross-Button-for-WPF
注意最后一项的红色文字