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

标签 c# wpf linq

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

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/

相关文章:

c# - 为什么我在用户 "Server"垃圾回收时会出现内存泄漏?

c# - 没有事件连接的运行方法

c# - "illegal project name"monoDevelop - Ubuntu?

c# - NHibernate 3、动态组件、字典和 LINQ 查询

.net - 如何使用 PRISM 创建 XAML 启动屏幕

c# - 更新 ViewModel 属性时如何避免递归?

c# - 具有完整对象访问权限的 LINQ Group-by

c# - MVC5/EF/LINQ - 多个选择计数查询返回到 View ,最佳实践

c# - 字段列表中的未知列 - MySQL 更改后

c# - WPF 和 XAML 中的 OxyPlot LineAnnotation 可见性