首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >FrameworkElementFactory中图像的Uri绑定

FrameworkElementFactory中图像的Uri绑定
EN

Stack Overflow用户
提问于 2011-06-07 04:06:33
回答 2查看 3.8K关注 0票数 1

我正在用代码创建DataTemplate,不能使用XAML。:(

我已经设法在模板中创建了一个图像,但前提是我硬编码了ico文件的路径。我希望能够将该字符串绑定到项目(我正在修改的ListView上使用DataTemplate )。

下面是我现在的代码:

代码语言:javascript
复制
private DataTemplate CreateDataTemplate(string binding, HorizontalAlignment alignment, bool active, bool useIcon)
{
    DataTemplate dt = new DataTemplate();

    FrameworkElementFactory sp = new FrameworkElementFactory(typeof(StackPanel));
    sp.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);

    if (useIcon)
    {
        double size = 14.0;
        BitmapImage bmp = new BitmapImage(new Uri("MyIcon.ico", UriKind.RelativeOrAbsolute));

        FrameworkElementFactory icon = new FrameworkElementFactory(typeof(Image));
        icon.SetValue(Image.SourceProperty, bmp);
        icon.SetValue(Image.WidthProperty, size);
        icon.SetValue(Image.HeightProperty, size);
        icon.SetValue(Image.MarginProperty, new Thickness(0, 0, 5, 0));
        sp.AppendChild(icon);
    }

    FrameworkElementFactory tb = new FrameworkElementFactory(typeof(TextBlock));
    tb.SetBinding(TextBlock.TextProperty, new Binding(binding));
    tb.SetValue(TextBlock.ForegroundProperty, (active ? Brushes.Black : Brushes.Gray));
    tb.SetValue(TextBlock.TextTrimmingProperty, TextTrimming.CharacterEllipsis);
    tb.SetValue(TextBlock.HorizontalAlignmentProperty, alignment);
    sp.AppendChild(tb);

    dt.VisualTree = sp;
    return dt;
}

谢谢!

EN

回答 2

Stack Overflow用户

发布于 2011-06-07 04:15:00

我想ValueConverter也可以工作。

代码语言:javascript
复制
public class StringToBitmapImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string uristring = value as string;
        return new BitmapImage(new Uri(uristring, UriKind.RelativeOrAbsolute));
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}
代码语言:javascript
复制
icon.SetBinding(Image.SourceProperty, new Binding(path) { Converter = new StringToBitmapImageConverter() });

其中path是指向在模板化对象中保存uri字符串的属性的属性路径。

票数 2
EN

Stack Overflow用户

发布于 2013-09-04 00:31:08

IValueConverter是这里的解决方案。不过,要注意pack URI语法!如果图像不是您的解决方案的一部分,则您的Convert方法应如下所示:

代码语言:javascript
复制
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
   return "pack://siteoforigin:,,,/" + (string)value;
}

请注意,图像文件需要与您的应用程序二进制文件位于相同的目录中,或者位于其子目录中,因为前导"../"将被自动剥离。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6257416

复制
相关文章

相似问题

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