首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Wpf DataTemplate

Wpf DataTemplate
EN

Stack Overflow用户
提问于 2010-09-17 19:00:32
回答 1查看 483关注 0票数 1

我已经为ListView定义了一个DataTemplate来显示fileInfo详细信息。这是DataTemplate

代码语言:javascript
复制
<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> 

ListViewImagesSourceList<FileInfo>

我必须根据文件的扩展名在列表中添加一个自定义图标。是否可以将扩展传递给一个方法,以获取现有DataTemplate中的图标路径?

EN

回答 1

Stack Overflow用户

发布于 2010-09-17 20:23:42

你需要一个转换器:

代码语言:javascript
复制
[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();
    }

}

然后,您需要在资源中声明转换器的实例:

代码语言:javascript
复制
<Window.Resources>
    <local:FileIconConverter x:Key="iconConverter" />
</Window.Resources>

并在绑定中使用它,如下所示:

代码语言:javascript
复制
<Image Source="{Binding FullName, Converter={StaticResource iconConverter}}" />
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3734724

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档