在FrameworkElementFactory中对图像进行Uri绑定

问题描述

| 我正在用代码创建DataTemplate,并且不能使用XAML。 :( 我设法在模板中创建了一个图像,但前提是我必须硬编码ico文件的路径。我希望能够将该字符串绑定到项目(我在修改的ListView上使用DataTemplate)。 现在是我的代码
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,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;
}
谢谢!     

解决方法

        我想ValueConverter可以工作。
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,System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}
icon.SetBinding(Image.SourceProperty,new Binding(path) { Converter = new StringToBitmapImageConverter() });
其中“ 3”是一个属性路径,它指向在模板对象内持有uri字符串的属性。     ,        解决方案是
IValueConverter
。注意包URI语法! 如果图像不属于您的解决方案,则您的
Convert
方法应如下所示:
public object Convert(object value,CultureInfo culture)
{
   return \"pack://siteoforigin:,/\" + (string)value;
}
请注意,映像文件必须与应用程序二进制文件位于同一目录或其子目录中,因为前导的“ 7”将被自动剥离。