Создать виртуальную копию элемента сетки и добавить в документ XPSC#

Место общения программистов C#
Ответить
Anonymous
 Создать виртуальную копию элемента сетки и добавить в документ XPS

Сообщение Anonymous »

Мое приложение создает из некоторого пользовательского ввода, некоторых уникальных чисел и отображает их как QR -коды, чтобы их можно было распечатать. < /p>
Это функция, с которой я сталкиваюсь проблема.private void Button_Click(object sender, RoutedEventArgs e)
{
listBox10.Visibility = Visibility.Collapsed;
PrintGrid.Visibility = Visibility.Visible;

GenerateUniqueNumber_v2.PrintTemplate printTemplate = new GenerateUniqueNumber_v2.PrintTemplate();

// Create a temporary ListBox to hold items for printing
ListBox tempListBox = new ListBox();

// Create a list to hold the filled templates
List filledTemplates = new List();

// Iterate over the items in the ListBox
for (int i = 0; i < listBox10.Items.Count; i++)
{
// Add the current item to the temporary ListBox
tempListBox.Items.Add(listBox10.Items);

// Check if we have collected 6 items or if we are at the last item
if ((i + 1) % 6 == 0 || i == listBox10.Items.Count - 1)
{
// Call the print method with the current batch of items
var filledTemplate = printTemplate.FillPrintGridTemplate(tempListBox);
filledTemplates.Add(filledTemplate); // Add the filled template to the list
filledTemplate = null;
//filledTemplates.Add(printTemplate.FillPrintGridTemplate(tempListBox));
//Print_WPF_Preview(printTemplate.FillPrintGridTemplate(tempListBox));
// Clear the temporary ListBox for the next batch
tempListBox.Items.Clear();
tempListBox = new ListBox();
//printTemplate.Close();
}
}

Print_WPF_Preview(filledTemplates);

//printTemplate.Show();
// Close the print template if needed
//printTemplate.Close();
}
< /code>
У меня есть Listbox с включенными элементами. Поскольку на одной странице печати можно отобразить только 6 элементов, я проверяю, когда у меня есть 6 элементов или у меня есть последний элемент, и передаю их методу FillPrintGridTemplate. < /P>
В этом окне я Создал шаблонную сетку, где я заполняю каждый раз, когда она передает элементы WPF, и возвращаю впоследствии сетку. Одна страница с правильными QR -кодами, которые должны быть распечатаны. Но как только есть более 6 пунктов, я получаю 2 или более страниц в моем документе XPS, что является правильным, но на каждой странице я получаю одинаковые QR -коды и информацию. < /P>
Я понял, когда прохожу здесь: < /p>
var filledTemplate = printTemplate.FillPrintGridTemplate(tempListBox);
< /code>
Scecond Time, первый элемент в моем списке заполненных образцов становится перезаписанным. Я предполагаю, что это потому, что я использую одну и ту же сетку и перезаписываю ее каждый раз.public Grid FillPrintGridTemplate(ListBox listBox)
{
Grid virtualGrid = new Grid();

Label[] wnrLabels = { lbl_WNR1, lbl_WNR2, lbl_WNR3, lbl_WNR4, lbl_WNR5, lbl_WNR6 };
Label[] UniqueNumberLabels = { lbl_UniqueNumber1, lbl_UniqueNumber2, lbl_UniqueNumber3, lbl_UniqueNumber4, lbl_UniqueNumber5, lbl_UniqueNumber6 };
Label[] MATNRLabels = { lbl_MATNR1, lbl_MATNR2, lbl_MATNR3, lbl_MATNR4, lbl_MATNR5, lbl_MATNR6 };
Image[] QRCodeImage = { qrCodeImage1, qrCodeImage2, qrCodeImage3, qrCodeImage4, qrCodeImage5, qrCodeImage6 };

ResetElements(wnrLabels, UniqueNumberLabels, MATNRLabels, QRCodeImage);

// Iterate over each item in the ListView
int i = 0;

foreach (var obj in listBox.Items)
{
// Cast the item to UniqueNumberItem
UniqueNumberItem item = obj as UniqueNumberItem;

if (item != null)
{
// Now that we've ensured 'item' is a UniqueNumberItem, we can access its properties
wnrLabels.Content = item.WNR;
UniqueNumberLabels.Content = item.UniqueNumber;
MATNRLabels.Content = item.Matnr;

// Generate QR code for the Unique Number
BitmapImage qrCodeImage = GenerateQRCode(item.UniqueNumber);
// Set the Image control's Source to the QR code
QRCodeImage.Source = qrCodeImage;

i++; // Move to the next index for the next item
}
}

return MainGrid;
}

Я подумал о том, можно ли создать что-то вроде клона сетки или каких-то временных элементов сетки, конечно же, с их дочерними элементами. Поэтому я не буду каждый раз перезаписывать одну и ту же сетку и решу свою проблему. Или есть какой-нибудь лучший способ сделать это?
Просто чтобы дать вам представление, вот как это выглядит. Я также каждый раз получаю случайный чистый лист бумаги, но, думаю, это еще одна проблема
[img]https://i.sstatic.net /TMYDurXJ.png[/img]

public static void Print_WPF_Preview(List wpf_Elements)
{
string sPrintFileName = "print_preview.xps";

if (File.Exists(sPrintFileName))
{
File.Delete(sPrintFileName);
}

// Create XPS document
using (XpsDocument doc = new XpsDocument(sPrintFileName, FileAccess.ReadWrite))
{
XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc);
SerializerWriterCollator output_Document = writer.CreateVisualsCollator();
output_Document.BeginBatchWrite();

// Iterate over each FrameworkElement and write it to the document
foreach (var element in wpf_Elements)
{
output_Document.Write(element);
// Add a new page for each element
output_Document.Write(new PageContent());
}

output_Document.EndBatchWrite();

// Open the document for preview
FixedDocumentSequence preview = doc.GetFixedDocumentSequence();
GenerateUniqueNumber_v2.PrintWindow printWindow = new GenerateUniqueNumber_v2.PrintWindow(preview);
printWindow.Show();
}
}


Подробнее здесь: https://stackoverflow.com/questions/793 ... s-document
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»