我正在尝试使用WPF用户控件从数据集生成大量图像,其中数据集中的每个项目都会产生一个图像...
我希望能够设置它,以便我可以使用WPF数据绑定,对于数据集中的每个项目,创建我的用户控件的实例,设置对应于我的数据项的依赖属性,然后将用户控件绘制到图像上,但我在让这一切工作时遇到了问题(不确定是数据绑定还是绘制到图像的问题)。
抱歉,代码很长,但我已经尝试了几个小时,WPF就是不喜欢我(不过总得学习一下...)
我的用户控件如下所示:
<UserControl x:Class="Bleargh.ImageTemplate"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:Bleargh"
x:Name="ImageTemplateContainer"
Height="300" Width="300">
<Canvas>
<TextBlock Canvas.Left="50" Canvas.Top="50" Width="200" Height="25" FontSize="16" FontFamily="Calibri" Text="{Binding Path=Booking.Customer, ElementName=ImageTemplateContainer}" />
<TextBlock Canvas.Left="50" Canvas.Top="100" Width="200" Height="25" FontSize="16" FontFamily="Calibri" Text="{Binding Path=Booking.Location, ElementName=ImageTemplateContainer}" />
<TextBlock Canvas.Left="50" Canvas.Top="150" Width="200" Height="25" FontSize="16" FontFamily="Calibri" Text="{Binding Path=Booking.ItemNumber, ElementName=ImageTemplateContainer}" />
<TextBlock Canvas.Left="50" Canvas.Top="200" Width="200" Height="25" FontSize="16" FontFamily="Calibri" Text="{Binding Path=Booking.Description,ElementName=ImageTemplateContainer}" />
</Canvas>
</UserControl>
我已经在我的用户控件中添加了一个名为 "Booking" 类型的依赖属性,希望它将成为数据绑定值的来源:
public partial class ImageTemplate : UserControl
{
public static readonly DependencyProperty BookingProperty = DependencyProperty.Register("Booking", typeof(Booking), typeof(ImageTemplate));
public Booking Booking
{
get { return (Booking)GetValue(BookingProperty); }
set { SetValue(BookingProperty, value); }
}
public ImageTemplate()
{
InitializeComponent();
}
}
我正在使用以下代码渲染控件:
List<Booking> bookings = Booking.GetSome();
for(int i = 0; i < bookings.Count; i++)
{
ImageTemplate template = new ImageTemplate();
template.Booking = bookings[i];
RenderTargetBitmap bitmap = new RenderTargetBitmap(
(int)template.Width,
(int)template.Height,
120.0,
120.0,
PixelFormats.Pbgra32);
bitmap.Render(template);
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
using (Stream s = File.OpenWrite(@"C:\Code\Bleargh\RawImages\" + i.ToString() + ".png"))
{
encoder.Save(s);
}
}
编辑:
我应该补充说明,该过程没有任何错误,但最终我得到的是一个充满纯白色图像的目录,而不是文本或其他内容......并且我已经使用调试器确认了我的预订对象被填充了正确的数据......
编辑2:
我做了一件我早就应该做的事情,在我的画布上设置了一个背景,但这并没有改变输出图像,所以我的问题肯定与我的绘图代码有关(尽管我的数据绑定可能有问题)。