我有一个充满文件路径的可观察集合,例如:
C:/Documents/1.png
我想将它们全部转换成文件名并用作我的列表框的 itemsSource 但 observablecollection 没有 convertAll 方法
ObservableCollection<string> InputEpisodes = new ObservableCollection<String>();
filesFoundListBox.ItemsSource = InputEpisodes.ConvertAll(x => Path.GetFileName(x));
最佳答案
创建一个从文件路径转换为文件名的绑定(bind)转换器:
public class FileNameConverter : IValueConverter
{
public object Convert(
object value, Type targetType, object parameter, CultureInfo culture)
{
return Path.GetFileName((string)value);
}
public object ConvertBack(
object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
然后像这样在您的 ListBox 中使用它:
<Window.Resources>
<local:FileNameConverter x:Key="FileNameConverter"/>
</Window.Resources>
...
<ListBox x:Name="filesFoundListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource FileNameConverter}}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
您现在可以直接将 InputEpisodes
集合分配给 ListBox 的 ItemsSource:
filesFoundListBox.ItemsSource = InputEpisodes;
关于c# - 将可观察的路径集合转换为文件名集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41779948/