使WPF ListBox逗号分隔值

时间:2013-11-01 19:07:00

标签: c# .net wpf xaml listbox

我有一个如下所示的ListBox:

<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>

这给了我一个这样的列表:

  

橘子,葡萄,香蕉,

但我想要的是:

  

橘子,葡萄,香蕉

(没有尾随逗号)

任何人都知道如何删除尾随逗号?

2 个答案:

答案 0 :(得分:4)

可以使用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>

答案 1 :(得分:1)

如果您重构代码,则可以非常轻松地创建一个具有所需结果的字符串:

string.Join(", ", Fruits) // e.g. Oranges, Grapes, Bananas

E.g。你可以:

// on your binding object
public string FruitString { get { return string.Join(", ", Fruits); } }
// in your XAML
<TextBlock Text="{Binding FruitString}" />

(或者,如果Fruits属性属于您定义的类,则可以覆盖其ToString(),这将是放置Join代码的好地方