我为ListView定义了一个DataTemplate来显示fileInfo的详细信息。 这是DataTemplate
<DataTemplate x:Key="srchFileListTemplate">
<StackPanel>
<WrapPanel>
<TextBlock FontWeight="Bold" FontFamily="Century Gothic"
Text="FileName :"/>
<TextBlock Margin="10,0,0,0" FontWeight="Bold"
FontFamily="Century Gothic" Text="{Binding Path=Name}"/>
</WrapPanel>
<WrapPanel>
<TextBlock FontFamily="Century Gothic" Text="FilePath :"/>
<TextBlock Margin="20,0,0,0" FontFamily="Century Gothic"
Text="{Binding Path = DirectoryName}"/>
</WrapPanel>
<WrapPanel>
<TextBlock FontFamily="Century Gothic" Text="File Size :"/>
<TextBlock Margin="20,0,0,0" FontFamily="Century Gothic"
Text="{Binding Path = Length}"/>
<TextBlock Text="Bytes"/>
</WrapPanel>
<WrapPanel>
<TextBlock FontFamily="Century Gothic" Text="File Extension:"/>
<TextBlock Margin="20,0,0,0" FontFamily="Century Gothic"
Text="{Binding Path = Extension}"/>
</WrapPanel>
</StackPanel>
</DataTemplate>
ImagesSource
的{p> ListView
为List<FileInfo>
我必须根据文件的扩展名将自定义图标添加到列表中。是否可以将扩展传递给方法以获取现有DataTemplate中的图标路径?
答案 0 :(得分:3)
你需要一个转换器:
[ValueConversion(typeof(string), typeof(ImageSource))]
public class FileIconConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string fileName = value as string;
if (fileName == null)
return null;
return IconFromFile(fileName);
}
private ImageSource IconFromFile(string fileName)
{
// logic to get the icon based on the filename
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// The opposite conversion doesn't make sense...
throw new NotImplementedException();
}
}
然后,您需要在资源中声明转换器的实例:
<Window.Resources>
<local:FileIconConverter x:Key="iconConverter" />
</Window.Resources>
您可以在绑定中使用它,如下所示:
<Image Source="{Binding FullName, Converter={StaticResource iconConverter}}" />