gpt4 book ai didi

c# - 使 WPF ListBox 逗号分隔值

转载 作者:太空狗 更新时间:2023-10-29 23:15:25 24 4
gpt4 key购买 nike

我有一个如下所示的列表框:

<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

(没有尾随逗号)

有人知道如何删除尾随逗号吗?

最佳答案

这可以通过使用 IValueConverter 来实现确定它的最后一项是否在列表框中,并通过使用 XAML 中的数据触发器更新绑定(bind)上的 StringFormat

创建一个转换器以确定值是否是列表框中的最后一项 -

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>

关于c# - 使 WPF ListBox 逗号分隔值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19733671/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com