最终目标:打印使用WPF和MVVM一个二维条码:WritableBitmap到的ImageSource在MVVM
背景资料(可能不相关),我有我的解决方案两个项目。一个项目控制我的业务逻辑,第二个项目控制打印逻辑,创建和打印标签。我为IPC使用命名管道。我使用MVVM并使用Xaml模板来设计标签,并在运行时填充其属性并打印它。这一切都正常工作。
更多信息:(可能相关)我正在使用创建二维条形码的第三方库。这是工作和呼叫,使条码返回一个可写的位图
问题: 我试图到可写的位图数据绑定到我的模板图像控制。
public void FooBar(string[] LabelProperties)
{
try
{
BarcodeWriter writer = new BarcodeWriter()
{
Format = BarcodeFormat.PDF_417,
Options = new ZXing.Common.EncodingOptions
{
Height = 50,
Width = 132,
Margin = 0
}
};
var wb = writer.Write("Some String");
System.Windows.Controls.Image newImage = new System.Windows.Controls.Image()
{
Height = 50,
HorizontalAlignment = HorizontalAlignment.Left,
Name = "image",
Stretch = Stretch.None,
VerticalAlignment = VerticalAlignment.Top,
Width = 132,
Source = wb,
};
this.BarCodeImage = newImage;
}
catch (Exception e)
{
Console.WriteLine(e.Message.ToString().Trim());
}
}
其值得注意的是,我不能直接WritableBitmap放置到BarCodeImage.Source
this.BarCodeImage.Source = wb;
,因为我使用的MVVM的设计,BarCodeImage不是实例,所以如果我尝试设置一些东西给它的来源,它会抛出一个空引用。
的XAML模板
<Image Height="50"
HorizontalAlignment="Left"
Margin="10,2,0,0"
Name="image"
Stretch="None"
VerticalAlignment="Top"
Width="132"
Source="{Binding lblBarCodeImage}" />
我的思想因为我有实例化一个新的Controls.Image(),然后设置,到BarCodeImage它在某种程度上打破这一点。
其他事项我可以显示其他类和settup证明我的MVVM是settup正确的,但所有其他控件数据绑定正确的 - 尽管他们是我数据绑定的所有字符串 - 没有其他的图像控制。
我也曾尝试的WritableBitmap转换成字节数组,tried using this solution, but that also did not work
哪里'lblBarCodeImage'财产宣称你在XAML中的'Source'绑定中使用?将'wb'分配给该属性。除此之外,不要在后面的代码中创建UI元素(如'System.Windows.Controls.Image')。声明它们并在XAML中绑定它们的属性。 – Clemens
@Clemens我在后面的执行过程中将lblBarCodeImage设置为this.BarCodeImage。 FooBar调用返回一个包含我想要绑定的所有值的对象。然后我将该对象传递给我的视图模型,在该模型中它被设置为lblBarCodeImage属性。我认为这是正常工作,因为我有其他字符串,我没有正常工作的例子。你认为我的问题是在后面的代码中创建Controls.image吗? – Brandon
查看我的回答... – Clemens