零售标签打印应用:如何在DiscountService类引用PrintLabels的WeekNum变量?
零售标签打印应用颜色初始化问题处理
问题背景
我们有一款简易零售标签打印应用,包含选择项表格与数量设置,涉及两个核心类:
PrintLabels类:内部计算并使用表示当前年周数的WeekNum变量public类DiscountService:包含CurrentColorCode变量(共6种颜色,按周循环切换)
当前问题:当手动选择非循环规则的颜色后关闭应用,重新打开时会因dat文件已保存该自定义颜色,导致显示与当前周数不匹配的错误颜色。需要修改DiscountService类,通过引用WeekNum来初始化对应周数的起始颜色。
现有代码
DiscountService类代码
public int CurrentColorCode { get { return currentColorCode; } set { // Ensure the color code is in range if (value < colorList.Count) { scheduledColor = currentColorCode = value; } else { currentColorCode = colorList.Count; } } }
PrintLabels类代码
private void pd_PrintPage(object sender, PrintPageEventArgs e) { DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo; DateTime d = DateTime.Today; Calendar cal = dfi.Calendar; int WeekNum = cal.GetWeekOfYear(d, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); if (WeekNum > 52) { DateTime newYear = d.AddDays(7); int newYearWeekNum = cal.GetWeekOfYear(newYear, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); if (newYearWeekNum == 2) { WeekNum = 1; } } e.Graphics.DrawImage(generateBarcode(barcodeString),58, 50); }
解决方案
1. 提取周数计算为公共可复用方法
将PrintLabels内的周数计算逻辑抽离为静态公共方法,方便DiscountService调用:
// 在PrintLabels类中添加静态方法 public static int GetCurrentWeekNum() { DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo; DateTime d = DateTime.Today; Calendar cal = dfi.Calendar; int weekNum = cal.GetWeekOfYear(d, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); if (weekNum > 52) { DateTime newYear = d.AddDays(7); int newYearWeekNum = cal.GetWeekOfYear(newYear, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); if (newYearWeekNum == 2) { weekNum = 1; } } return weekNum; }
2. 修改DiscountService类添加周数初始化逻辑
在DiscountService的构造方法或初始化流程中,调用公共周数方法,通过取模计算对应周的初始颜色:
public class DiscountService { private List<int> colorList; // 假设已定义的6种颜色列表 private int currentColorCode; private int scheduledColor; public int CurrentColorCode { get => currentColorCode; set { if (value < colorList.Count) { scheduledColor = currentColorCode = value; } else { currentColorCode = colorList.Count; } } } // 构造时自动按周初始化颜色 public DiscountService() { // 此处确保colorList已完成初始化(如colorList = new List<int> {0,1,2,3,4,5};) InitializeColorByWeek(); } private void InitializeColorByWeek() { int weekNum = PrintLabels.GetCurrentWeekNum(); // 按6种颜色循环,计算当前周对应的初始颜色代码 int initialColor = (weekNum - 1) % colorList.Count; CurrentColorCode = initialColor; } // 公开初始化方法,用于应用重启加载dat文件后重置颜色 public void ResetColorToWeekDefault() { InitializeColorByWeek(); } }
3. 应用重启时的处理逻辑
当应用重新启动并加载dat文件后,若检测到当前颜色不符合周循环规则,调用ResetColorToWeekDefault()方法,将颜色重置为当前周的默认值。
内容的提问来源于stack exchange,提问作者noobice94
相关产品推荐
相关产品推荐

