【发布时间】:2016-08-02 02:04:12
【问题描述】:
最终目标:使用 WPF 和 MVVM 打印二维条码:
背景信息(可能不相关)我的解决方案中有两个项目。一个项目控制我的业务逻辑,第二个项目控制标签的打印逻辑、创建和打印。我正在为 IPC 使用命名管道。我正在使用 MVVM 并有一个 Xaml 模板来设计标签,并在运行时填充它的属性并打印它。这一切正常。
更多信息:(可能相关)我正在使用创建二维条码的第三方库。这是有效的,使条形码返回一个可写位图的调用
问题: 我正在尝试将可写位图数据绑定到模板上的 Image 控件。
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 它以某种方式打破了这一点。
其他事情我可以显示其他类和设置以证明我的 MVVM 设置正确,但所有其他控件都正确数据绑定 - 尽管它们都是我正在数据绑定的字符串 - 没有其他图像控制。
我也试过将 WritableBitmap 转换为字节数组和tried using this solution, but that also did not work
【问题讨论】:
-
在 XAML 的
Source绑定中声明的lblBarCodeImage属性在哪里?将wb分配给该属性。除此之外,不要在后面的代码中创建 UI 元素(如System.Windows.Controls.Image)。在 XAML 中声明它们并绑定它们的属性。 -
@Clemens 我在稍后的执行中将 lblBarCodeImage 设置为 this.BarCodeImage。 FooBar 调用返回一个对象,其中包含我要绑定的所有值。然后我将该对象传递给我的视图模型,在该模型中它被设置为 lblBarCodeImage 属性。我认为这工作正常,因为我在示例中遗漏了其他正常工作的字符串。你认为我的问题是在后面的代码中创建 Controls.image 吗?