1

我在代码中创建一个 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, 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;
}

谢谢!

4

2 回答 2

2

我想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, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}
icon.SetBinding(Image.SourceProperty, new Binding(path) { Converter = new StringToBitmapImageConverter() });

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

于 2011-06-06T20:14:59.663 回答
0

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

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
   return "pack://siteoforigin:,,,/" + (string)value;
}

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

于 2013-09-03T16:31:08.380 回答