结束目标:使用WPF和MVVM打印二维条码:
背景信息(可能不相关)我的解决方案中有两个项目。一个项目控制我的业务逻辑,第二个项目控制打印逻辑,创建和打印标签。我正在使用IPC的命名管道。我正在使用MVVM并使用Xaml模板来设计标签,并在运行时填充其属性并进行打印。这一切都正常。
更多信息:(可能相关)我正在使用创建二维条形码的第三方库。这是有效的,并且调用条形码返回一个可写位图
ISSUE: 我试图将可写位图数据绑定到我的模板上的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没有实例化,因此如果我尝试将某些东西设置为Source,它会抛出一个空引用。
模板中的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
答案 0 :(得分:2)
不要在后面的代码中创建一个Image控件!
相反,声明类型为ImageSource
的视图模型属性,并在XAML中将Image控件的Source
属性绑定到该视图模型属性。
查看型号:
public class YourViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private ImageSource barCodeImage;
public ImageSource BarCodeImage
{
get { return barCodeImage; }
set
{
barCodeImage = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("BarCodeImage"));
}
}
...
}
XAML:
<Image ... Source="{Binding BarCodeImage}"/>
在代码后面,将WriteableBitmap分配给BarCodeImage
属性:
yourViewModel.BarCodeImage = wb;
答案 1 :(得分:0)
您应该具有BitmapImage属性,如下所示:
private BitmapImage photoSelected;
public BitmapImage PhotoSelected
{
get { return photoSelected; }
set { photoSelected = value; OnPropertyChanged("PhotoSelected"); }
}
然后就你想要的动作做到这一点:
PhotoSelected = new BitmapImage(new Uri(@"pack://application:,,,/Images/4.png"));
将/Images/4.png替换为从解决方案级别开始的图像路径。例如,这就是我的解决方案树在达到这一点时的样子:
XAML用于绑定:
<Image x:Name="BitMapImage" Source="{Binding PhotoSelected, Mode=TwoWay}" RenderOptions.BitmapScalingMode="HighQuality"/>