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