这可以使用IValueConverter来确定其是否last item in a listBox and there by updating StringFormat on your binding using data trigger in XAML
.
创建一个转换器来确定值是否是列表框中的最后一项 -
public class IsLastItemInContainerConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
CultureInfo culture)
{
DependencyObject item = (DependencyObject)value;
ItemsControl ic = ItemsControl.ItemsControlFromItemContainer(item);
return ic.ItemContainerGenerator.IndexFromContainer(item) ==
ic.Items.Count - 1;
}
public object ConvertBack(object value, Type targetType, object parameter,
CultureInfo culture)
{
throw new NotImplementedException();
}
}
现在修改您的 XAML 并在 DataTemplate 上添加触发器以从 TextBlock 上的 StringFormat 中删除逗号 -
<ListBox ItemsSource="{Binding Fruits}">
<ListBox.Resources>
<local:IsLastItemInContainerConverter
x:Key="IsLastItemInContainerConverter"/>
</ListBox.Resources>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock x:Name="textBlock"
Text="{Binding Name, StringFormat=' {0},'}" />
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource
Mode=FindAncestor,
AncestorType=ListBoxItem},
Converter={StaticResource IsLastItemInContainerConverter}}"
Value="True">
<Setter Property="Text" TargetName="textBlock"
Value="{Binding Name, StringFormat=' {0}'}"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>