我正在 Maui Android 中使用 DrawView 来获取人的标志。我完美地获取图像流,使用该图像创建 pdf,然后完美导航到下一个视图。我正在绑定按钮标志的启用属性 MVVM,以允许在进行任何绘制后保存图像。它可以完美地完成所有事情。 但这是我的问题,在获取图像和创建 pdf 的过程中,我尝试禁用按钮的属性以避免用户交互,但它们不会更改用户界面上的状态... 我再说一遍,MVVM 模式工作得很好。所有过程都运行良好。 我正在尝试另一件事,即在此过程中显示弹出窗口,然后在导航到下一页时将其关闭。但弹出窗口不显示,它显示我何时导航到下一页。
是否是因为在获取图像的过程中,用户界面被冻结,该视图中无法显示任何内容?
我只使用内容页面代码,因为 MVVM 工作正常...
提前储罐
<Grid
RowDefinitions=".8*,.2*"
ColumnDefinitions="*,*">
<toolkit:DrawingView
x:Name="DrawView"
Grid.ColumnSpan="2"
LineColor="Black"
LineWidth="5"
IsMultiLineModeEnabled="True"
ShouldClearOnFinish="False"
DrawingLineStartedCommand="{Binding EnableSignButtonCommand}"
Margin="15"/>
<ActivityIndicator
IsRunning="{Binding ActivityIndicatorEnable}"
Grid.Row="1"/>
<Button
Grid.Row="1"
Text="Cancelar"
IsEnabled="{Binding IsCancelButtonEnabled}"
HorizontalOptions="Center"
VerticalOptions="Center"
WidthRequest="120"
HeightRequest="70"
BackgroundColor="Red"
FontSize="Medium"
Command="{Binding CancelCommand}"/>
<Button
Grid.Row="1"
Grid.Column="1"
Text="Guardar"
IsEnabled="{Binding IsSignButtonEnabled}"
HorizontalOptions="Center"
VerticalOptions="Center"
WidthRequest="120"
HeightRequest="70"
FontSize="Medium"
BackgroundColor="Green"
Command="{Binding GeneratePdfCommand}"/>
</Grid>
我需要知道为什么我无法在我的视图中显示更改
这是我的 MVVM 模型,太长了..
public partial class SignViewModel : ObservableObject
{
public string orderReferenceView { get; set; }
public string orderClientView { get; set; }
[ObservableProperty]
public bool activityIndicatorEnable;
PdfGeneratingPopup pdfPopup = new PdfGeneratingPopup();
[ObservableProperty]
public bool isSignButtonEnabled =false;
[ObservableProperty]
public bool isCancelButtonEnabled = true;
public Order currentOrder { get; set; }
private readonly IDrawView _drawView;
[RelayCommand]
private void EnableSignButton()
{
IsSignButtonEnabled=true;
}
public SignViewModel(IDrawView drawView)
{
_drawView = drawView;
orderReferenceView = App.GlobalVariablesRepo.savedOrder.Reference;
orderClientView = App.GlobalVariablesRepo.savedOrder.Client.razon_social;
currentOrder = App.OrdersRepo.GetItemsWithChildren().Where(x => x.Id ==
App.GlobalVariablesRepo.savedOrder.Id).FirstOrDefault();
}
private async Task ShowPopup()
{
var firstPopup = new PdfGeneratingPopup();
Shell.Current.ShowPopup(pdfPopup);
}
[RelayCommand]
private void Cancel()
{
Shell.Current.GoToAsync("..");
}
private async void GetImage()
{
using var stream = await _drawView.GetImageStream(200, 200);
using var memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
stream.Position = 0;
memoryStream.Position = 0;
#如果安卓 var context = Platform.CurrentActivity;
if (OperatingSystem.IsAndroidVersionAtLeast(29))
{
Android.Content.ContentResolver resolver = context.ContentResolver;
Android.Content.ContentValues contentValues = new();
contentValues.Put(Android.Provider.MediaStore.IMediaColumns.DisplayName, "sign.png");
contentValues.Put(Android.Provider.MediaStore.IMediaColumns.MimeType, "image/png");
contentValues.Put(Android.Provider.MediaStore.IMediaColumns.RelativePath, "DCIM/" + "prueba");
Android.Net.Uri imageUri = resolver.Insert(Android.Provider.MediaStore.Images.Media.ExternalContentUri, contentValues);
var os = resolver.OpenOutputStream(imageUri);
Android.Graphics.BitmapFactory.Options options = new();
options.InJustDecodeBounds = true;
var bitmap = Android.Graphics.BitmapFactory.DecodeStream(stream);
bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, os);
os.Flush();
os.Close();
}
else
{
Java.IO.File storagePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures);
string path = System.IO.Path.Combine(storagePath.ToString(), "sign.png");
System.IO.File.WriteAllBytes(path, memoryStream.ToArray());
var mediaScanIntent = new Android.Content.Intent(Android.Content.Intent.ActionMediaScannerScanFile);
mediaScanIntent.SetData(Android.Net.Uri.FromFile(new Java.IO.File(path)));
context.SendBroadcast(mediaScanIntent);
}
#endif }
[RelayCommand]
private async void GeneratePdf()
{
ActivityIndicatorEnable = true;
IsCancelButtonEnabled = false;
IsSignButtonEnabled = false;
string oldImagePath = System.IO.Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, "DCIM", "prueba", "sign.png");
if (!System.IO.File.Exists(oldImagePath))
{
System.IO.File.Delete(oldImagePath);
}
GetImage();
//Shell.Current.ShowPopup(pdfPopup);
#如果安卓 字符串文件名 = $"{orderReferenceView}.pdf";
string dcimPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim).AbsolutePath;
string imagePath = Path.Combine(dcimPath, "prueba", "sign.png");
string documentsPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments).AbsolutePath;
string pedidosPath = Path.Combine(documentsPath, "pedidos");
// Crear el directorio si no existe
if (!Directory.Exists(pedidosPath))
{
Directory.CreateDirectory(pedidosPath);
}
var filePath = Path.Combine(pedidosPath, fileName);
using (PdfWriter writer = new PdfWriter(filePath))
{
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf);
Paragraph header = new Paragraph(orderReferenceView)
.SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER)
.SetFontSize(20);
document.Add(header);
//*************************
//// Añadir encabezado con logo
//Image logo = new Image(ImageDataFactory.Create("ruta/del/logo.png")) // Ruta de la imagen del logo
// .SetWidth(50) // Ajustar el ancho del logo
// .SetHeight(50) // Ajustar el alto del logo
// .SetTextAlignment(TextAlignment.LEFT) // Alinear a la izquierda
// .SetHorizontalAlignment(HorizontalAlignment.LEFT) // Alinear a la izquierda
// .SetMarginTop(10); // Margen superior para el logo
//Paragraph header = new Paragraph()
// .Add(logo)
// .Add(new Text("\n")) // Añadir un salto de línea después del logo
// .Add(new Text("Encabezado de tu PDF"))
// .SetTextAlignment(TextAlignment.CENTER);
//document.Add(header); // Añadir el encabezado al documento
//*************************
Paragraph subheader = new Paragraph(orderClientView)
.SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER)
.SetFontSize(15);
document.Add(subheader);
LineSeparator ls = new LineSeparator(new SolidLine());
document.Add(ls);
Table table = new Table(new float[] { 17, 3 }); // Primera columna ocupa el 85% y la segunda el 15%
table.SetWidth(UnitValue.CreatePercentValue(100));
// Encabezados de las columnas
Cell cellArticulo = new Cell(1, 1).Add(new Paragraph("Artículo"));
cellArticulo.SetWidth(UnitValue.CreatePercentValue(85)); // Ancho del 85%
cellArticulo.SetTextAlignment(TextAlignment.CENTER);
cellArticulo.SetBackgroundColor(new DeviceRgb(225, 225, 225));
Cell cellCantidad = new Cell(1, 1).Add(new Paragraph("Cantidad"));
cellCantidad.SetWidth(UnitValue.CreatePercentValue(15)); // Ancho del 15%
cellCantidad.SetTextAlignment(TextAlignment.CENTER);
cellCantidad.SetBackgroundColor(new DeviceRgb(225, 225, 225));
// Añadir los encabezados a la tabla
table.AddHeaderCell(cellArticulo);
table.AddHeaderCell(cellCantidad);
//Añadir los datos
foreach (var item in currentOrder.OrderLines)
{
Cell cellItem = new Cell(1, 1).Add(new Paragraph(item.ProductReference.ToString()));
cellItem.SetTextAlignment(TextAlignment.CENTER); // Alinear al centro
Cell cellQuantity = new Cell(1, 1).Add(new Paragraph(item.Quantity.ToString()));
cellQuantity.SetTextAlignment(TextAlignment.CENTER); // Alinear al centro
table.AddCell(cellItem); // Añadir el artículo
table.AddCell(cellQuantity); // Añadir la cantidad
}
document.Add(table);
//Añadir la imagen
ImageData imageData = ImageDataFactory.Create(imagePath);
iText.Layout.Element.Image image = new iText.Layout.Element.Image(imageData)
.SetHorizontalAlignment(iText.Layout.Properties.HorizontalAlignment.CENTER)
.SetFontSize(15)
.SetFontColor(iText.Kernel.Colors.ColorConstants.LIGHT_GRAY)
.SetWidth(75) // Definir el ancho deseado
.SetHeight(50) // Definir la altura deseada
.SetMarginTop(20) // Definir el margen superior
.SetMarginBottom(20) // Definir el margen inferior
.SetMarginLeft(50) // Definir el margen izquierdo
.SetMarginRight(50); // Definir el margen derecho
document.Add(image);
Paragraph footer = new Paragraph("Don't forget to like and subscribe!")
.SetTextAlignment(iText.Layout.Properties.TextAlignment.RIGHT);
document.Add(footer);
Console.WriteLine("PDF guardado en: " + filePath);
document.Close();
//Eliminar el archivo Sign para que no llenar la memoria del Android
if (System.IO.File.Exists(imagePath))
{
System.IO.File.Delete(imagePath);
}
currentOrder.StatusId = 2;
App.OrdersRepo.UpdateItemChildren(currentOrder);
ActivityIndicatorEnable = false;
Shell.Current.GoToAsync("PrintPdf");
}