2010-09-17 74 views
1

我已經爲ListView定義了一個DataTemplate來顯示fileInfo的詳細信息。 這是DataTemplate中Wpf 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> 

ImagesSourceListViewList<FileInfo>

我必須根據文件添加到列表的擴展添加自定義圖標。是否可以將擴展傳遞給一個方法來獲取現有DataTemplate中的圖標路徑?

回答

2

你需要一個轉換器:

[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}}" /> 
+0

我遇到的問題是圖像源不是靜態的,我必須根據擴展名獲取圖像源,並且必須在在列表視圖的數據模板中包含圖像 – sugirthini 2010-09-20 10:18:36

+0

我不理解您的評論...您是指「將圖像包含在數據模板中」是什麼意思? – 2010-09-20 12:09:10