Skip to main content
 首页 » 编程设计

c#之将可观察的路径集合转换为文件名集合

2024年02月27日36mengfanrong

我有一个充满文件路径的可观察集合,例如:

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;