使WPF ListBox逗号分隔值
问题描述:
我有一个看起来像这样的ListBox:
I have a ListBox that looks like this:
<ListBox ItemsSource="{Binding Fruits}">
<!--Make the items wrap-->
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel></WrapPanel>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name, StringFormat=' {0},'}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
这会给我这样的列表:
橘子,葡萄,香蕉,
Oranges, Grapes, Bananas,
但是我想要的是:
桔子,葡萄,香蕉
Oranges, Grapes, Bananas
(不带逗号)
有人知道如何删除结尾的逗号吗?
答
Create a converter to determine if value is last item in listbox -
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中删除逗号-
Now modify your XAML and add trigger on DataTemplate to remove comma from StringFormat on your TextBlock -
<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>