Мое приложение создает на основе введенных пользователем данных уникальные числа и отображает их в виде QR-кодов, чтобы их можно было распечатать.
Это функция, в которой я работаю. столкнулся с проблемой.
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 through 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>
У меня есть Liledbox, который включали элементы. Поскольку на одной странице печати можно отобразить только 6 элементов, я проверяю, когда у меня есть 6 элементов, или у меня последний элемент, и передаю их на метод FillPrintGridTemplate. В этом окне я создал шаблонную сетку, где я заполняю каждый раз, когда она передает элементы WPF, и возвращаю впоследствии сетку. И я получаю одну страницу с правильными QR-кодами, которые должны быть распечатаны. Но как только в моем документе XPS будет более 6 пунктов, я получаю 2 или более страниц на своем XPS Document, но на каждой странице я получаю одинаковые QR-коды и информацию. < /P>
Я выяснил, когда я прохожу здесь: var Fullytemplate = printTemplate.fillPrintGridtemplate (Templistbox); Scecond Time, первый элемент в моем списке заполненных образцов. Я предполагаю, что это потому, что я использую одну и ту же сетку и перезаписываю ее каждый раз. < /P>
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 through 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;
}
Итак, я подумал о том, можно ли создать что-то вроде клона сетки или некоторых временных элементов сетки, конечно, с их дочерними элементами. Поэтому я не буду каждый раз перезаписывать одну и ту же сетку и решу свою проблему. Или есть лучший способ сделать это?
Просто чтобы дать вам представление, вот как это выглядит. Я также каждый раз получаю случайный чистый лист бумаги, но я думаю, это еще одна проблема
введите описание изображения здесь
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
Создать виртуальную копию элемента сетки и добавить в документ XPS ⇐ C#
Место общения программистов C#
-
Anonymous
1737798979
Anonymous
Мое приложение создает на основе введенных пользователем данных уникальные числа и отображает их в виде QR-кодов, чтобы их можно было распечатать.
Это функция, в которой я работаю. столкнулся с проблемой.
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 through 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[i]);
// 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>
У меня есть Liledbox, который включали элементы. Поскольку на одной странице печати можно отобразить только 6 элементов, я проверяю, когда у меня есть 6 элементов, или у меня последний элемент, и передаю их на метод FillPrintGridTemplate. В этом окне я создал шаблонную сетку, где я заполняю каждый раз, когда она передает элементы WPF, и возвращаю впоследствии сетку. И я получаю одну страницу с правильными QR-кодами, которые должны быть распечатаны. Но как только в моем документе XPS будет более 6 пунктов, я получаю 2 или более страниц на своем XPS Document, но на каждой странице я получаю одинаковые QR-коды и информацию. < /P>
Я выяснил, когда я прохожу здесь: var Fullytemplate = printTemplate.fillPrintGridtemplate (Templistbox); Scecond Time, первый элемент в моем списке заполненных образцов. Я предполагаю, что это потому, что я использую одну и ту же сетку и перезаписываю ее каждый раз. < /P>
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 through 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[i].Content = item.WNR;
UniqueNumberLabels[i].Content = item.UniqueNumber;
MATNRLabels[i].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[i].Source = qrCodeImage;
i++; // Move to the next index for the next item
}
}
return MainGrid;
}
Итак, я подумал о том, можно ли создать что-то вроде клона сетки или некоторых временных элементов сетки, конечно, с их дочерними элементами. Поэтому я не буду каждый раз перезаписывать одну и ту же сетку и решу свою проблему. Или есть лучший способ сделать это?
Просто чтобы дать вам представление, вот как это выглядит. Я также каждый раз получаю случайный чистый лист бумаги, но я думаю, это еще одна проблема
введите описание изображения здесь
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();
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79386496/create-a-virtual-copy-of-grid-element-and-add-to-xps-document[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия