Make a WPF ListBox comma separate values(制作 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>
这给了我一个这样的列表:
This gives me a list like this:
橙子、葡萄、香蕉、
但我想要的是:
橙子、葡萄、香蕉
(无尾随逗号)
有人知道如何删除尾随逗号吗?
推荐答案
这可以使用 IValueConverter 通过使用 XAML 中的数据触发器更新绑定上的 StringFormat 来确定其 listBox 中的最后一项是否存在.
This can be achieved using IValueConverter to determine whether its last item in a listBox and there by updating StringFormat on your binding using data trigger in XAML.
创建一个转换器来确定值是否是列表框中的最后一项 -
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>
这篇关于制作 WPF ListBox 逗号分隔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:制作 WPF ListBox 逗号分隔值
基础教程推荐
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
