[英]Convert observablecollection of paths into collection of filenames
我有可觀察的集合填充文件的路徑,例如:
C:/Documents/1.png
我想將它們全部轉換為文件名並用作我的列表框的itemsSource但observablecollection沒有convertAll方法
ObservableCollection<string> InputEpisodes = new ObservableCollection<String>();
filesFoundListBox.ItemsSource = InputEpisodes.ConvertAll(x => Path.GetFileName(x));
創建一個綁定轉換器,從文件路徑轉換為文件名:
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;
好吧,雖然使用綁定轉換器的答案很好,但如果您可能需要來自文件的更多信息,最好創建一個包含FileName
, Path
, FileSize
等必需屬性的FileInformation
類...
通過這種方式,您可以更輕松地為列表框添加不同的演示文稿,並且您還可以保留原始路徑,如果您需要獲取信息,可能會在以后使用(如果您有可能的話,您可以使用給定文件名的多個副本)允許來自多個目錄的文件)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.