我正在用代码创建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;
}谢谢!
发布于 2011-06-07 04:15:00
我想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() });其中path是指向在模板化对象中保存uri字符串的属性的属性路径。
发布于 2013-09-04 00:31:08
IValueConverter是这里的解决方案。不过,要注意pack URI语法!如果图像不是您的解决方案的一部分,则您的Convert方法应如下所示:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return "pack://siteoforigin:,,,/" + (string)value;
}请注意,图像文件需要与您的应用程序二进制文件位于相同的目录中,或者位于其子目录中,因为前导"../"将被自动剥离。
https://stackoverflow.com/questions/6257416
复制相似问题