删除了一些测试方法

新增了刀序重排确认窗口
优化了应用刀序到钻带后的一些操作
This commit is contained in:
2025-12-13 12:30:36 +08:00
parent b866365968
commit 3cdf68651f
8 changed files with 595 additions and 854 deletions

View File

@@ -172,6 +172,7 @@ namespace DrillTools
if (sourceIndex != -1 && targetIndex != -1 && sourceIndex != targetIndex) if (sourceIndex != -1 && targetIndex != -1 && sourceIndex != targetIndex)
{ {
// 执行重排
viewModel?.ReorderTools(sourceIndex, targetIndex); viewModel?.ReorderTools(sourceIndex, targetIndex);
Debug.WriteLine($"[DragDrop] 重新排序完成: {sourceIndex} -> {targetIndex}"); Debug.WriteLine($"[DragDrop] 重新排序完成: {sourceIndex} -> {targetIndex}");
} }

View File

@@ -1,180 +0,0 @@
# GenerateReorderedDrillTape 方法实现方案
## 目标
`GenerateReorderedDrillTape` 静态扩展方法的功能升级,使其与 `ReorderAndRenumberTools` 方法完全一致。
## 当前问题分析
现有的 `GenerateReorderedDrillTape` 方法只实现简单的重排功能,缺少以下关键特性:
1. 刀具重新编号T01, T02, T03...
2. 机台码智能处理(保持原始编号)
3. 完整的钻带内容重构逻辑
4. 数据映射和同步机制
## 新实现方案
### 1. 方法签名保持不变
```csharp
public static string GenerateReorderedDrillTape(string originalDrillTape, List<ToolItem> reorderedTools)
```
### 2. 核心实现逻辑
#### 步骤1: 创建刀具编号映射
```csharp
// 1. 创建原始刀具编号到新编号的映射
var toolNumberMapping = new Dictionary<int, int>();
var originalToNewMapping = new Dictionary<int, int>();
// 2. 按当前列表顺序重新编号T01, T02, T03...
int newToolNumber = 1;
foreach (var tool in reorderedTools)
{
// 机台码刀具不允许重新编号
if (tool.ToolType != ToolType.MachineCode)
{
originalToNewMapping[tool.ToolNumber] = newToolNumber;
toolNumberMapping[tool.ToolNumber] = newToolNumber;
tool.ToolNumber = newToolNumber++;
}
else
{
// 机台码刀具保持原始编号,但也要加入映射
toolNumberMapping[tool.ToolNumber] = tool.ToolNumber;
}
}
```
#### 步骤2: 解析原始钻带内容
```csharp
// 解析原始钻带中的刀具定义行,保存参数信息
var originalToolDefinitions = new Dictionary<int, string>();
var headerLines = new List<string>();
var lines = originalDrillTape.Split(new[] { '\r', '\n' }, StringSplitOptions.None);
foreach (var line in lines)
{
string trimmedLine = line.Trim();
if (trimmedLine == "%")
{
break;
}
// 处理刀具定义行(如 T01C1.049H05000Z+0.000S060.00F105.0U0700.0
if (Regex.IsMatch(trimmedLine, @"^T(\d+)C"))
{
var match = Regex.Match(trimmedLine, @"^T(\d+)C(.*)$");
if (match.Success)
{
int originalToolNumber = int.Parse(match.Groups[1].Value);
originalToolDefinitions[originalToolNumber] = match.Groups[2].Value;
}
}
else
{
if (line != "")
headerLines.Add(line);
}
}
```
#### 步骤3: 重构刀具定义部分
```csharp
// 按照新的刀具编号顺序输出刀具定义部分
var sortedTools = reorderedTools.OrderBy(t => t.ToolNumber).ToList();
foreach (var tool in sortedTools)
{
// 查找原始刀具编号
int originalToolNumber = -1;
foreach (var kvp in toolNumberMapping)
{
if (kvp.Value == tool.ToolNumber)
{
originalToolNumber = kvp.Key;
break;
}
}
if (originalToolNumber != -1 && originalToolDefinitions.ContainsKey(originalToolNumber))
{
string toolDef = $"T{tool.ToolNumber:D2}C{originalToolDefinitions[originalToolNumber]}";
result.Add(toolDef);
}
}
```
#### 步骤4: 处理坐标数据和机台码
```csharp
// 按新刀具编号顺序输出刀具切换行和对应的坐标数据
var sortedToolsForData = reorderedTools.OrderBy(t => t.ToolNumber).ToList();
foreach (var tool in sortedToolsForData)
{
// 添加刀具切换行
result.Add($"T{tool.ToolNumber:D2}");
// 添加该刀具对应的所有坐标数据
if (tool.ToolType != ToolType.MachineCode && tool.HoleLocations != null && tool.HoleLocations.Count > 0)
{
foreach (var location in tool.HoleLocations)
{
result.Add(location);
}
}
// 如果是机台码刀具,添加机台码命令和坐标
if (tool.ToolType == ToolType.MachineCode)
{
if (!string.IsNullOrEmpty(tool.MachineCodeCommand) && !string.IsNullOrEmpty(tool.MachineCodeType))
{
result.Add($"{tool.MachineCodeCommand},{tool.MachineCodeType},$S $N");
// 添加机台码的坐标数据
if (tool.HoleLocations != null && tool.HoleLocations.Count > 0)
{
foreach (var location in tool.HoleLocations)
{
result.Add(location);
}
}
}
}
}
```
### 3. 关键特性实现
#### 机台码处理逻辑
- 机台码刀具保持原始编号不变
- 机台码命令M97/M98和类型A*/B*)正确保留
- 机台码坐标数据完整保留
#### 数据映射机制
- 创建原始编号到新编号的完整映射
- 支持混合编号场景(部分重新编号)
- 确保坐标数据正确绑定到对应刀具
#### 钻带内容重构
- 完整保留原始刀具参数
- 按新编号顺序重新组织钻带结构
- 确保格式和语法正确性
### 4. 实现优势
1. **功能一致性**: 与 `ReorderAndRenumberTools` 方法功能完全一致
2. **向后兼容**: 保持原有方法签名,现有调用代码无需修改
3. **健壮性**: 完整的错误处理和边界条件检查
4. **可维护性**: 清晰的代码结构和注释
### 5. 测试验证
需要验证以下场景:
1. 普通刀具重排和重新编号
2. 机台码刀具保持原始编号
3. 混合场景(部分机台码、部分普通刀具)
4. 坐标数据正确绑定
5. 钻带格式正确性
## 实现建议
建议切换到 Code 模式进行实际的代码修改,因为 Architect 模式只能编辑 Markdown 文件。实现时应严格按照上述方案进行,确保与 `ReorderAndRenumberTools` 方法的行为完全一致。

View File

@@ -24,11 +24,11 @@
<!-- 工具栏 --> <!-- 工具栏 -->
<ToolBar Grid.Row="0"> <ToolBar Grid.Row="0">
<Button <!--<Button
Name="LoadSampleDataButton" Name="LoadSampleDataButton"
Click="LoadSampleDataButton_Click" Click="LoadSampleDataButton_Click"
Content="加载示例数据" /> Content="加载示例数据" />
<Separator /> <Separator />-->
<Button <Button
Name="LoadDrillTapeButton" Name="LoadDrillTapeButton"
Click="LoadDrillTapeButton_Click" Click="LoadDrillTapeButton_Click"

View File

@@ -18,15 +18,6 @@ namespace DrillTools
var viewModel = new MainWindowViewModel(); var viewModel = new MainWindowViewModel();
DataContext = viewModel; DataContext = viewModel;
InitializeDragDrop(); InitializeDragDrop();
// 测试修正后的重排刀序功能
// TestReorderDemo.RunDemo();
// 测试机台码孔数计算功能
//viewModel.TestMachineCodeHoleCalculation();
// 测试机台码处理修复效果
viewModel.TestMachineCodeProcessingFix();
} }
/// <summary> /// <summary>
@@ -100,6 +91,11 @@ namespace DrillTools
ViewModel.DrillTapeContent = reorderedDrillTape; ViewModel.DrillTapeContent = reorderedDrillTape;
System.Windows.MessageBox.Show("刀序重排完成", "提示", MessageBoxButton.OK, MessageBoxImage.Information); System.Windows.MessageBox.Show("刀序重排完成", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
} }
catch (OperationCanceledException)
{
// 用户取消操作,不显示错误消息
System.Diagnostics.Debug.WriteLine("用户取消了刀序重排操作");
}
catch (Exception ex) catch (Exception ex)
{ {
System.Windows.MessageBox.Show($"重排刀序失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error); System.Windows.MessageBox.Show($"重排刀序失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
@@ -113,7 +109,7 @@ namespace DrillTools
{ {
try try
{ {
string reorderedDrillTape = ViewModel.ApplyToolOrderToDrillTape(); string reorderedDrillTape = ViewModel.ReorderAndRenumberTools(true);
ViewModel.DrillTapeContent = reorderedDrillTape; ViewModel.DrillTapeContent = reorderedDrillTape;
System.Windows.MessageBox.Show("刀具顺序已应用到钻带", "提示", MessageBoxButton.OK, MessageBoxImage.Information); System.Windows.MessageBox.Show("刀具顺序已应用到钻带", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
} }

View File

@@ -8,6 +8,7 @@ using System.Runtime.CompilerServices;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Windows; using System.Windows;
using DrillTools.Integration; using DrillTools.Integration;
using System.Diagnostics;
namespace DrillTools namespace DrillTools
{ {
@@ -17,6 +18,7 @@ namespace DrillTools
public class MainWindowViewModel : INotifyPropertyChanged public class MainWindowViewModel : INotifyPropertyChanged
{ {
private ObservableCollection<ToolItem> _tools = new(); private ObservableCollection<ToolItem> _tools = new();
private ObservableCollection<ToolItem> _originalTools = new(); // 保存原始刀具顺序
private ToolItem? _selectedTool; private ToolItem? _selectedTool;
private string _drillTapeContent = string.Empty; private string _drillTapeContent = string.Empty;
private bool _canMoveUp; private bool _canMoveUp;
@@ -90,6 +92,15 @@ namespace DrillTools
} }
} }
/// <summary>
/// 原始刀具顺序集合(按文件中的出现顺序)
/// </summary>
public ObservableCollection<ToolItem> OriginalTools
{
get => _originalTools;
set => SetProperty(ref _originalTools, value);
}
/// <summary> /// <summary>
/// 是否有原始文件 /// 是否有原始文件
/// </summary> /// </summary>
@@ -103,6 +114,7 @@ namespace DrillTools
{ {
DrillTapeContent = drillTapeContent; DrillTapeContent = drillTapeContent;
Tools.Clear(); Tools.Clear();
OriginalTools.Clear(); // 清空原始刀具顺序
try try
{ {
@@ -164,6 +176,20 @@ namespace DrillTools
} }
Tools.Add(toolItem); Tools.Add(toolItem);
// 同时添加到原始刀具顺序集合中
var originalToolItem = new ToolItem
{
ToolNumber = toolResult.ToolNumber,
Diameter = toolResult.Diameter,
ToolType = toolResult.ToolType,
ToolSuffixType = toolResult.ToolSuffixType,
ToolCategory = toolResult.ToolCategory,
HoleLocations = toolResult.Locations ?? new List<string>(),
MachineCodeCommand = toolResult.MachineCodeCommand,
MachineCodeType = toolResult.MachineCodeType
};
OriginalTools.Add(originalToolItem);
} }
// 更新按钮状态 // 更新按钮状态
@@ -398,6 +424,9 @@ namespace DrillTools
// 4. 更新当前钻带内容 // 4. 更新当前钻带内容
DrillTapeContent = reorderedDrillTape; DrillTapeContent = reorderedDrillTape;
// 5. 打开文件资源管理器并选中文件
OpenFileExplorerAndSelectFile(OriginalFilePath);
return reorderedDrillTape; return reorderedDrillTape;
} }
catch (OperationCanceledException) catch (OperationCanceledException)
@@ -415,18 +444,71 @@ namespace DrillTools
/// 重排刀序并重新编号 /// 重排刀序并重新编号
/// </summary> /// </summary>
/// <returns>重排后的钻带内容</returns> /// <returns>重排后的钻带内容</returns>
public string ReorderAndRenumberTools() public string ReorderAndRenumberTools(bool isApply = false)
{ {
if (Tools.Count == 0) if (Tools.Count == 0)
{ {
throw new InvalidOperationException("没有可重排的刀具"); throw new InvalidOperationException("没有可重排的刀具");
} }
// 保存原始刀具列表(按文件中的原始顺序)
var originalTools = OriginalTools.Select(t => new ToolItem
{
ToolNumber = t.ToolNumber,
Diameter = t.Diameter,
ToolType = t.ToolType,
ToolSuffixType = t.ToolSuffixType,
ToolCategory = t.ToolCategory,
HoleLocations = new List<string>(t.HoleLocations ?? new List<string>()),
MachineCodeCommand = t.MachineCodeCommand,
MachineCodeType = t.MachineCodeType
}).ToList();
// 1. 创建原始刀具编号到新编号的映射 // 1. 创建原始刀具编号到新编号的映射
var toolNumberMapping = new Dictionary<int, int>();
var originalToNewMapping = new Dictionary<int, int>(); // 保存原始映射关系 // 创建重排后的刀具列表(基于用户已调整的顺序)
// 注意Tools 列表已经反映了用户通过拖放操作调整后的顺序
var reorderedTools = new List<ToolItem>();
reorderedTools = Tools.Select(t => new ToolItem
{
ToolNumber = t.ToolNumber,
Diameter = t.Diameter,
ToolType = t.ToolType,
ToolSuffixType = t.ToolSuffixType,
ToolCategory = t.ToolCategory,
HoleLocations = new List<string>(t.HoleLocations ?? new List<string>()),
MachineCodeCommand = t.MachineCodeCommand,
MachineCodeType = t.MachineCodeType
}).ToList();
//检查是否所有刀序没有变化
int checkindex = 1;
for (int i = 0; i < originalTools.Count; i++)
{
if (reorderedTools[i].ToolNumber == originalTools[i].ToolNumber)
checkindex++;
}
if (checkindex == originalTools.Count)
{
if (isApply)
{
ApplyToolOrderToDrillTape();
return DrillTapeContent;
}
throw new InvalidOperationException("刀具顺序未发生变化,无需重排");
}
// 显示确认窗口
var confirmationWindow = new ToolReorderConfirmationWindow(originalTools, reorderedTools);
confirmationWindow.Owner = System.Windows.Application.Current.MainWindow;
confirmationWindow.ShowDialog();
if (!confirmationWindow.IsConfirmed)
throw new OperationCanceledException("取消刀序重排操作");
// 2. 按当前列表顺序重新编号T01, T02, T03... // 2. 按当前列表顺序重新编号T01, T02, T03...
var toolNumberMapping = new Dictionary<int, int>();
var originalToNewMapping = new Dictionary<int, int>(); // 保存原始映射关系
int newToolNumber = 1; int newToolNumber = 1;
foreach (var tool in Tools.ToList()) foreach (var tool in Tools.ToList())
{ {
@@ -453,6 +535,9 @@ namespace DrillTools
// 5. 更新界面显示 // 5. 更新界面显示
OnPropertyChanged(nameof(Tools)); OnPropertyChanged(nameof(Tools));
if (isApply)
ApplyToolOrderToDrillTape();
return updatedDrillTape; return updatedDrillTape;
} }
@@ -587,6 +672,7 @@ namespace DrillTools
// 清空原始文件路径,因为这是示例数据 // 清空原始文件路径,因为这是示例数据
OriginalFilePath = string.Empty; OriginalFilePath = string.Empty;
Tools.Clear(); Tools.Clear();
OriginalTools.Clear(); // 清空原始刀具顺序
// 添加示例刀具数据 // 添加示例刀具数据
Tools.Add(new ToolItem Tools.Add(new ToolItem
@@ -709,6 +795,23 @@ namespace DrillTools
HoleLocations = new List<string> { "X-194000Y002000" } // 机台码刀具的坐标数据 HoleLocations = new List<string> { "X-194000Y002000" } // 机台码刀具的坐标数据
}); });
// 同时添加到原始刀具顺序集合中
foreach (var tool in Tools)
{
var originalToolItem = new ToolItem
{
ToolNumber = tool.ToolNumber,
Diameter = tool.Diameter,
ToolType = tool.ToolType,
ToolSuffixType = tool.ToolSuffixType,
ToolCategory = tool.ToolCategory,
HoleLocations = new List<string>(tool.HoleLocations ?? new List<string>()),
MachineCodeCommand = tool.MachineCodeCommand,
MachineCodeType = tool.MachineCodeType
};
OriginalTools.Add(originalToolItem);
}
// 更新按钮状态 // 更新按钮状态
UpdateMoveButtonsState(); UpdateMoveButtonsState();
@@ -779,114 +882,6 @@ M30";
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
} }
/// <summary>
/// 测试机台码孔数计算功能
/// </summary>
public void TestMachineCodeHoleCalculation()
{
Console.WriteLine("=== 机台码孔数计算测试 ===");
// 测试钻带内容
string drillTapeContent = @"M48
;厚铜板参数-镀膜-EA-250618
T01C0.799H05000Z+0.000S060.00F105.0U0700.0
T02C0.656H01500Z+0.150S070.00F008.0U0800.0
T03C1.601H03000Z-0.200S040.00F030.0U0900.0
T04C0.499
%
T01
X-167525Y013500
X-167525Y018500
X-167525Y023500
X167525Y013500
X167525Y018500
X167525Y023500
X099366Y502000
T02
X-065975Y115250
X-085825Y122450
X-085825Y124550
X-097425Y115250
X103093Y502000
T03
X-069659Y016450G85X-094159Y016450
X-181341Y195550G85X-156841Y195550
X-069659Y210450G85X-094159Y210450
X-181341Y389550G85X-156841Y389550
X-069659Y404450G85X-094159Y404450
X-181341Y583550G85X-156841Y583550
X162939Y596000
T04
M97,A*,$S $N
X-194000Y002000
M30";
// 处理钻带
var result = DrillTapeProcessor.ProcessDrillTape(drillTapeContent);
// 输出结果
Console.WriteLine($"处理状态: {(result.Success ? "" : "")}");
if (!result.Success)
{
Console.WriteLine($"错误信息: {result.Message}");
return;
}
Console.WriteLine("\n刀具统计:");
Console.WriteLine("刀具\t孔径(mm)\t类型\t\t普通孔数\t槽孔数\t总孔数\t孔位数量");
Console.WriteLine("========================================================================");
foreach (var tool in result.ToolResults)
{
string toolTypeDisplay = tool.ToolType switch
{
ToolType.Regular => "圆孔",
ToolType.Slot => "槽孔",
ToolType.MachineCode => "机台码",
_ => "未知"
};
Console.WriteLine($"T{tool.ToolNumber:D2}\t{tool.Diameter:F3}\t\t{toolTypeDisplay}\t{tool.RegularHoles}\t\t{tool.SlotHoles}\t{tool.TotalHoles}\t{tool.Locations?.Count ?? 0}");
}
Console.WriteLine($"\n总孔数: {result.TotalHoles}");
// 验证结果
Console.WriteLine("\n=== 验证结果 ===");
VerifyResults(result);
// 测试孔位数据
Console.WriteLine("\n=== 孔位数据测试 ===");
TestHoleLocations(result);
}
/// <summary>
/// 测试孔位数据
/// </summary>
/// <param name="result">钻带处理结果</param>
private void TestHoleLocations(DrillTapeResult result)
{
foreach (var tool in result.ToolResults)
{
Console.WriteLine($"\nT{tool.ToolNumber:D2} 孔位数据 ({tool.Locations?.Count ?? 0} 个):");
if (tool.Locations != null && tool.Locations.Count > 0)
{
foreach (var location in tool.Locations.Take(5)) // 只显示前5个
{
Console.WriteLine($" {location}");
}
if (tool.Locations.Count > 5)
{
Console.WriteLine($" ... 还有 {tool.Locations.Count - 5} 个孔位");
}
}
else
{
Console.WriteLine(" 无孔位数据");
}
}
}
private void VerifyResults(DrillTapeResult result) private void VerifyResults(DrillTapeResult result)
{ {
// CAM350的预期结果 // CAM350的预期结果
@@ -925,254 +920,6 @@ M30";
Console.WriteLine($"\n总体结果: {(allMatch ? " CAM350一致" : " ")}"); Console.WriteLine($"\n总体结果: {(allMatch ? " CAM350一致" : " ")}");
} }
/// <summary>
/// 测试刀具尾号类型功能
/// </summary>
public void TestToolSuffixTypeFunctionality()
{
Console.WriteLine("=== 刀具尾号类型功能测试 ===");
// 测试不同孔径的尾号类型
double[] testDiameters = { 1.049, 1.550, 1.156, 1.451, 1.153, 1.255, 1.266, 1.277, 1.288, 1.299 };
Console.WriteLine("孔径(mm)\t尾号\t尾号类型\t\t大类");
Console.WriteLine("==============================================");
foreach (double diameter in testDiameters)
{
string diameterStr = diameter.ToString("F3");
char lastChar = diameterStr[diameterStr.Length - 1];
int suffix = int.Parse(lastChar.ToString());
var suffixType = ToolItem.GetToolSuffixType(diameter);
var category = ToolItem.GetToolCategory(suffixType);
var suffixDisplay = ToolItem.GetToolSuffixTypeDisplay(suffixType);
var categoryDisplay = ToolItem.GetToolCategoryDisplay(category);
Console.WriteLine($"{diameter:F3}\t{suffix}\t{suffixDisplay}\t{categoryDisplay}");
}
Console.WriteLine();
Console.WriteLine("=== 测试钻带处理功能 ===");
// 测试钻带处理
string drillTapeContent = @"M48
T10C1.049
T11C1.550
T12C1.156
T13C1.451
T14C1.153
T15C1.255
T16C1.266
T17C1.277
%
T10
X01000Y01000
T11
X02000Y02000
T12
X03000Y03000
T13
X04000Y04000
T14
X05000Y05000
T15
X06000Y06000
T16
X07000Y07000
T17
X08000Y08000
M30";
var result = DrillTapeProcessor.ProcessDrillTape(drillTapeContent);
if (result.Success)
{
Console.WriteLine("钻带处理成功!");
Console.WriteLine();
Console.WriteLine("刀具编号\t孔径(mm)\t类型\t\t尾号类型\t大类\t\t孔数");
Console.WriteLine("================================================================");
foreach (var tool in result.ToolResults)
{
string toolTypeDisplay = tool.ToolType switch
{
ToolType.Regular => "圆孔",
ToolType.Slot => "槽孔",
ToolType.MachineCode => "机台码",
_ => "未知"
};
string suffixTypeDisplay = tool.ToolSuffixType switch
{
ToolSuffixType.Drill => "钻针",
ToolSuffixType.Slot => "槽刀",
ToolSuffixType.EASlot => "EA型槽刀",
ToolSuffixType.DustSlot => "粉尘刀",
ToolSuffixType.DeburrSlot => "去毛刺刀",
ToolSuffixType.NonStandard => "非标刀",
ToolSuffixType.EASlot2 => "EA型槽刀",
ToolSuffixType.Special => "特殊刀具",
_ => "未知"
};
string categoryDisplay = tool.ToolCategory switch
{
ToolCategory.Drill => "钻针",
ToolCategory.Slot => "槽刀",
ToolCategory.EA => "EA刀",
ToolCategory.NonStandard => "非标刀",
ToolCategory.Special => "特殊刀",
_ => "未知"
};
Console.WriteLine($"T{tool.ToolNumber:D2}\t{tool.Diameter:F3}\t\t{toolTypeDisplay}\t{suffixTypeDisplay}\t{categoryDisplay}\t{tool.TotalHoles}");
}
}
else
{
Console.WriteLine($"钻带处理失败: {result.Message}");
}
Console.WriteLine();
Console.WriteLine("测试完成!");
}
/// <summary>
/// 测试孔位数据功能(可在应用启动时调用)
/// </summary>
public static void TestHoleLocationsFunctionality()
{
Console.WriteLine("=== 孔位数据功能测试 ===");
Console.WriteLine();
// 使用用户提供的钻带数据示例
string drillTapeContent = @"M48
T01C0.799H05000Z+0.000S060.00F105.0U0700.0
T02C1.049H05000Z+0.000S045.00F105.0U0700.0
%
T01
X-281000Y003000
X-276000Y003000
X-271000Y003000
X271000Y003000
X276000Y003000
X281000Y003000
X-281000Y702500
X-276000Y702500
X-271000Y702500
X271000Y703000
X276000Y703000
X281000Y703000
X077370Y704000
T02
X-100000Y100000
X-200000Y200000
X-300000Y300000
M30";
// 处理钻带
var result = DrillTapeProcessor.ProcessDrillTape(drillTapeContent);
// 输出结果
Console.WriteLine($"处理状态: {(result.Success ? "" : "")}");
if (!result.Success)
{
Console.WriteLine($"错误信息: {result.Message}");
return;
}
Console.WriteLine("\n刀具统计:");
Console.WriteLine("刀具\t孔径(mm)\t类型\t\t普通孔数\t槽孔数\t总孔数\t孔位数量");
Console.WriteLine("========================================================================");
foreach (var tool in result.ToolResults)
{
string toolTypeDisplay = tool.ToolType switch
{
ToolType.Regular => "圆孔",
ToolType.Slot => "槽孔",
ToolType.MachineCode => "机台码",
_ => "未知"
};
Console.WriteLine($"T{tool.ToolNumber:D2}\t{tool.Diameter:F3}\t\t{toolTypeDisplay}\t{tool.RegularHoles}\t\t{tool.SlotHoles}\t{tool.TotalHoles}\t{tool.Locations?.Count ?? 0}");
}
Console.WriteLine($"\n总孔数: {result.TotalHoles}");
// 详细显示孔位数据
Console.WriteLine("\n=== 详细孔位数据 ===");
foreach (var tool in result.ToolResults)
{
Console.WriteLine($"\nT{tool.ToolNumber:D2} 孔位数据 ({tool.Locations?.Count ?? 0} 个):");
if (tool.Locations != null && tool.Locations.Count > 0)
{
int count = 0;
foreach (var location in tool.Locations)
{
Console.WriteLine($" [{++count:D2}] {location}");
}
}
else
{
Console.WriteLine(" 无孔位数据");
}
}
// 验证T01的孔位数据是否符合预期
Console.WriteLine("\n=== 验证T01孔位数据 ===");
var t01Result = result.ToolResults.Find(t => t.ToolNumber == 1);
if (t01Result != null && t01Result.Locations != null)
{
var expectedLocations = new System.Collections.Generic.List<string>
{
"X-281000Y003000",
"X-276000Y003000",
"X-271000Y003000",
"X271000Y003000",
"X276000Y003000",
"X281000Y003000",
"X-281000Y702500",
"X-276000Y702500",
"X-271000Y702500",
"X271000Y703000",
"X276000Y703000",
"X281000Y703000",
"X077370Y704000"
};
bool allMatch = true;
if (t01Result.Locations.Count == expectedLocations.Count)
{
for (int i = 0; i < expectedLocations.Count; i++)
{
if (t01Result.Locations[i] != expectedLocations[i])
{
Console.WriteLine($" 位置 {i + 1}: 预期 {expectedLocations[i]}, 实际 {t01Result.Locations[i]} ✗");
allMatch = false;
}
else
{
Console.WriteLine($" 位置 {i + 1}: {t01Result.Locations[i]} ✓");
}
}
}
else
{
Console.WriteLine($" 孔位数量不匹配: 预期 {expectedLocations.Count}, 实际 {t01Result.Locations.Count} ✗");
allMatch = false;
}
Console.WriteLine($"\nT01孔位数据验证结果: {(allMatch ? " " : " ")}");
}
else
{
Console.WriteLine("未找到T01刀具数据 ✗");
}
Console.WriteLine("\n孔位数据功能测试完成");
}
/// <summary> /// <summary>
/// 显示刀具详情窗口 /// 显示刀具详情窗口
/// </summary> /// </summary>
@@ -1296,311 +1043,32 @@ M30";
} }
/// <summary> /// <summary>
/// 测试修正后的重排刀序功能 /// 打开文件资源管理器并选中指定文件
/// </summary> /// </summary>
public void TestFixedReorderFunction() /// <param name="filePath">要选中的文件路径</param>
private void OpenFileExplorerAndSelectFile(string filePath)
{ {
Console.WriteLine("=== 测试修正后的重排刀序功能 ===");
// 1. 加载测试数据
LoadSampleData();
Console.WriteLine("原始刀具顺序:");
foreach (var tool in Tools)
{
Console.WriteLine($"T{tool.ToolNumber:D2}C{tool.Diameter:F3}");
}
// 2. 模拟用户重排操作将T02移到第一位
if (Tools.Count >= 2)
{
var toolToMove = Tools.FirstOrDefault(t => t.ToolNumber == 2);
if (toolToMove != null && toolToMove.ToolType != ToolType.MachineCode)
{
int oldIndex = Tools.IndexOf(toolToMove);
ReorderTools(oldIndex, 0);
Console.WriteLine("\n重排后刀具顺序重新编号前:");
foreach (var tool in Tools)
{
Console.WriteLine($"T{tool.ToolNumber:D2}C{tool.Diameter:F3}");
}
// 3. 执行重新编号
string reorderedDrillTape = ReorderAndRenumberTools();
Console.WriteLine("\n重排并重新编号后的刀具顺序:");
foreach (var tool in Tools)
{
Console.WriteLine($"T{tool.ToolNumber:D2}C{tool.Diameter:F3}");
}
// 4. 验证刀具定义部分是否按顺序排列
Console.WriteLine("\n=== 验证结果 ===");
var lines = reorderedDrillTape.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
var toolDefinitionOrder = new List<int>();
foreach (var line in lines)
{
if (line.Trim() == "%")
{
break;
}
if (Regex.IsMatch(line, @"^T(\d+)C"))
{
var match = Regex.Match(line, @"^T(\d+)C");
if (match.Success)
{
toolDefinitionOrder.Add(int.Parse(match.Groups[1].Value));
}
}
}
Console.WriteLine("刀具定义部分的顺序: " + string.Join(", ", toolDefinitionOrder.Select(t => $"T{t:D2}")));
bool isOrdered = true;
for (int i = 1; i < toolDefinitionOrder.Count; i++)
{
if (toolDefinitionOrder[i] < toolDefinitionOrder[i - 1])
{
isOrdered = false;
break;
}
}
Console.WriteLine($"刀具定义部分是否按顺序排列: {(isOrdered ? "" : "")}");
if (isOrdered)
{
Console.WriteLine("✓ 重排刀序功能修正成功!");
}
else
{
Console.WriteLine("✗ 重排刀序功能仍有问题!");
}
// 5. 显示完整的重排后钻带内容
Console.WriteLine("\n重排后的钻带内容:");
Console.WriteLine(reorderedDrillTape);
}
}
}
/// <summary>
/// 测试机台码坐标数据完整性
/// </summary>
public void TestMachineCodeCoordinateIntegrity()
{
Console.WriteLine("=== 机台码坐标数据完整性测试 ===");
// 1. 加载示例数据
LoadSampleData();
// 2. 执行重排刀序操作
string reorderedDrillTape = ReorderAndRenumberTools();
// 3. 验证机台码坐标数据
Console.WriteLine("重排后的钻带内容:");
Console.WriteLine(reorderedDrillTape);
// 4. 检查机台码部分是否包含坐标数据
var lines = reorderedDrillTape.Split(new[] { '\r', '\n' }, StringSplitOptions.None);
bool foundMachineCode = false;
bool foundCoordinate = false;
int machineCodeToolNumber = -1;
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i].Trim();
// 查找机台码刀具
if (Regex.IsMatch(line, @"^T(\d+)"))
{
var match = Regex.Match(line, @"^T(\d+)");
if (match.Success)
{
int toolNumber = int.Parse(match.Groups[1].Value);
var tool = Tools.FirstOrDefault(t => t.ToolNumber == toolNumber);
if (tool != null && tool.ToolType == ToolType.MachineCode)
{
foundMachineCode = true;
machineCodeToolNumber = toolNumber;
Console.WriteLine($"\n找到机台码刀具 T{toolNumber:D2}");
// 检查下一行是否是机台码命令
if (i + 1 < lines.Length)
{
string nextLine = lines[i + 1].Trim();
if (Regex.IsMatch(nextLine, @"(M97|M98),(A\*|B\*),\$S \$N"))
{
Console.WriteLine($" 机台码命令: {nextLine}");
// 检查下下行是否是坐标数据
if (i + 2 < lines.Length)
{
string coordinateLine = lines[i + 2].Trim();
if (Regex.IsMatch(coordinateLine, @"X([+-]?\d+\.?\d*)Y([+-]?\d+\.?\d*)"))
{
foundCoordinate = true;
Console.WriteLine($" 坐标数据: {coordinateLine}");
}
}
}
}
}
}
}
}
// 5. 输出测试结果
Console.WriteLine("\n=== 测试结果 ===");
Console.WriteLine($"找到机台码刀具: {(foundMachineCode ? "" : "")}");
Console.WriteLine($"找到坐标数据: {(foundCoordinate ? "" : "")}");
if (foundMachineCode && foundCoordinate)
{
Console.WriteLine("✓ 机台码坐标数据完整性测试通过!");
}
else
{
Console.WriteLine("✗ 机台码坐标数据完整性测试失败!");
if (!foundMachineCode)
Console.WriteLine(" 原因:未找到机台码刀具");
if (!foundCoordinate)
Console.WriteLine(" 原因:机台码刀具缺少坐标数据");
}
// 6. 验证ToolItem中的坐标数据
var machineCodeTool = Tools.FirstOrDefault(t => t.ToolType == ToolType.MachineCode);
if (machineCodeTool != null)
{
Console.WriteLine($"\nToolItem中的机台码坐标数据:");
Console.WriteLine($" 刀具编号: T{machineCodeTool.ToolNumber:D2}");
Console.WriteLine($" 机台码命令: {machineCodeTool.MachineCodeCommand}");
Console.WriteLine($" 机台码类型: {machineCodeTool.MachineCodeType}");
Console.WriteLine($" 坐标数量: {machineCodeTool.HoleLocations?.Count ?? 0}");
if (machineCodeTool.HoleLocations != null && machineCodeTool.HoleLocations.Count > 0)
{
foreach (var location in machineCodeTool.HoleLocations)
{
Console.WriteLine($" 坐标: {location}");
}
}
}
}
/// <summary>
/// 测试机台码处理修复效果
/// </summary>
public void TestMachineCodeProcessingFix()
{
Console.WriteLine("=== 测试机台码处理修复效果 ===");
// 测试钻带内容(包含机台码)
string testDrillTape = @"M48
;厚铜板参数-镀膜-EA-250618
T01C1.049H05000Z+0.000S060.00F105.0U0700.0
T02C1.550H01500Z+0.150S070.00F008.0U0800.0
T03C1.156H03000Z-0.200S040.00F030.0U0900.0
T04C0.499H01500Z+0.150S070.00F008.0U0800.0
%
T01
X-167525Y013500
X-167525Y018500
X-167525Y023500
T02
X-065975Y115250
X-085825Y122450
T03
X-069659Y016450G85X-094159Y016450
X-181341Y195550G85X-156841Y195550
T04
M97,A*,$S $N
X-194000Y002000
M30";
try try
{ {
// 1. 使用DrillTapeProcessor处理钻带 if (!File.Exists(filePath))
Console.WriteLine("\n1. 使用DrillTapeProcessor处理钻带:");
var result = DrillTapeProcessor.ProcessDrillTape(testDrillTape);
if (!result.Success)
{ {
Console.WriteLine($"处理失败: {result.Message}"); System.Windows.MessageBox.Show($"文件不存在: {filePath}", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
return; return;
} }
// 2. 检查ToolResult中的机台码信息 // 使用 explorer.exe 的 /select 参数来打开文件资源管理器并选中文件
Console.WriteLine("\n2. 检查ToolResult中的机台码信息:"); ProcessStartInfo startInfo = new ProcessStartInfo
foreach (var toolResult in result.ToolResults)
{ {
Console.WriteLine($"T{toolResult.ToolNumber:D2}: 类型={toolResult.ToolType}, 命令={toolResult.MachineCodeCommand}, 类型={toolResult.MachineCodeType}"); FileName = "explorer.exe",
} Arguments = $"/select,\"{filePath}\"",
UseShellExecute = true
};
// 3. 使用LoadToolsFromDrillTape方法加载到ViewModel Process.Start(startInfo);
Console.WriteLine("\n3. 加载到ViewModel并检查ToolItem中的机台码信息:");
DrillTapeContent = testDrillTape;
Tools.Clear();
LoadToolsFromDrillTape(testDrillTape);
foreach (var tool in Tools)
{
Console.WriteLine($"T{tool.ToolNumber:D2}: 类型={tool.ToolType}, 命令={tool.MachineCodeCommand}, 类型={tool.MachineCodeType}");
}
// 4. 测试GenerateReorderedDrillTape方法
Console.WriteLine("\n4. 测试GenerateReorderedDrillTape方法:");
string reorderedDrillTape = DrillTapeProcessorExtensions.GenerateReorderedDrillTape(testDrillTape, Tools.ToList());
Console.WriteLine("重排后的钻带内容:");
Console.WriteLine(reorderedDrillTape);
// 5. 验证机台码信息是否正确保留
Console.WriteLine("\n5. 验证机台码信息是否正确保留:");
bool machineCodeFound = false;
bool machineCodeCommandFound = false;
bool machineCodeTypeFound = false;
var lines = reorderedDrillTape.Split(new[] { '\r', '\n' }, StringSplitOptions.None);
foreach (var line in lines)
{
if (line.Contains("M97") || line.Contains("M98"))
{
machineCodeFound = true;
if (line.Contains("M97") || line.Contains("M98"))
{
machineCodeCommandFound = true;
}
if (line.Contains("A*") || line.Contains("B*"))
{
machineCodeTypeFound = true;
}
Console.WriteLine($"找到机台码命令行: {line}");
}
}
Console.WriteLine($"\n验证结果:");
Console.WriteLine($"机台码命令存在: {machineCodeFound}");
Console.WriteLine($"机台码命令类型正确: {machineCodeCommandFound}");
Console.WriteLine($"机台码类型正确: {machineCodeTypeFound}");
if (machineCodeFound && machineCodeCommandFound && machineCodeTypeFound)
{
Console.WriteLine("\n✓ 机台码处理修复效果验证成功!");
}
else
{
Console.WriteLine("\n✗ 机台码处理修复效果验证失败!");
}
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine($"测试过程中发生异常: {ex.Message}"); System.Windows.MessageBox.Show($"打开文件资源管理器失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
Console.WriteLine($"堆栈跟踪: {ex.StackTrace}");
} }
} }
} }

View File

@@ -0,0 +1,201 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows.Media;
using Brush = System.Windows.Media.Brush;
namespace DrillTools
{
/// <summary>
/// 刀序重排确认窗口视图模型
/// </summary>
public class ToolReorderConfirmationViewModel : INotifyPropertyChanged
{
private ObservableCollection<ToolOrderItem> _originalTools = new();
private ObservableCollection<ToolOrderItem> _reorderedTools = new();
/// <summary>
/// 原始刀具列表
/// </summary>
public ObservableCollection<ToolOrderItem> OriginalTools
{
get => _originalTools;
set => SetProperty(ref _originalTools, value);
}
/// <summary>
/// 重排后刀具列表
/// </summary>
public ObservableCollection<ToolOrderItem> ReorderedTools
{
get => _reorderedTools;
set => SetProperty(ref _reorderedTools, value);
}
/// <summary>
/// 构造函数
/// </summary>
public ToolReorderConfirmationViewModel()
{
}
/// <summary>
/// 使用原始和重排后的刀具列表初始化
/// </summary>
/// <param name="originalTools">原始刀具列表</param>
/// <param name="reorderedTools">重排后刀具列表</param>
public ToolReorderConfirmationViewModel(IEnumerable<ToolItem> originalTools, IEnumerable<ToolItem> reorderedTools) : this()
{
LoadTools(originalTools, reorderedTools);
}
/// <summary>
/// 加载刀具数据
/// </summary>
/// <param name="originalTools">原始刀具列表</param>
/// <param name="reorderedTools">重排后刀具列表</param>
public void LoadTools(IEnumerable<ToolItem> originalTools, IEnumerable<ToolItem> reorderedTools)
{
OriginalTools.Clear();
ReorderedTools.Clear();
// 创建原始刀具列表项
int order = 1;
foreach (var tool in originalTools)
{
OriginalTools.Add(new ToolOrderItem
{
Order = order++,
ToolNumber = tool.ToolNumber,
Diameter = tool.Diameter,
ToolTypeDisplay = tool.ToolTypeDisplay,
BackgroundColor = System.Windows.Media.Brushes.White
});
}
// 创建重排后刀具列表项,并比较位置变化
order = 1;
var originalToolList = originalTools.ToList();
var reorderedToolList = reorderedTools.ToList();
foreach (var tool in reorderedToolList)
{
// 查找该刀具在原始列表中的位置
int originalIndex = originalToolList.FindIndex(t => t.Diameter == tool.Diameter && t.ToolType == tool.ToolType);
int newIndex = reorderedToolList.IndexOf(tool);
// 判断位置是否发生变化
bool positionChanged = originalIndex != newIndex;
ReorderedTools.Add(new ToolOrderItem
{
Order = order++,
ToolNumber = tool.ToolNumber,
Diameter = tool.Diameter,
ToolTypeDisplay = tool.ToolTypeDisplay,
BackgroundColor = positionChanged ? new SolidColorBrush(System.Windows.Media.Color.FromRgb(255, 235, 238)) : new SolidColorBrush(System.Windows.Media.Color.FromRgb(232, 245, 233))
});
// 同时更新原始列表中对应项的背景色
if (originalIndex >= 0 && originalIndex < OriginalTools.Count)
{
OriginalTools[originalIndex].BackgroundColor = positionChanged ? new SolidColorBrush(System.Windows.Media.Color.FromRgb(255, 235, 238)) : new SolidColorBrush(System.Windows.Media.Color.FromRgb(232, 245, 233));
}
}
}
public event PropertyChangedEventHandler? PropertyChanged;
protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value))
return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}
protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
/// <summary>
/// 刀具排序项
/// </summary>
public class ToolOrderItem : INotifyPropertyChanged
{
private int _order;
private int _toolNumber;
private double _diameter;
private string _toolTypeDisplay = string.Empty;
private Brush _backgroundColor = System.Windows.Media.Brushes.White;
/// <summary>
/// 序号
/// </summary>
public int Order
{
get => _order;
set => SetProperty(ref _order, value);
}
/// <summary>
/// 刀具编号
/// </summary>
public int ToolNumber
{
get => _toolNumber;
set => SetProperty(ref _toolNumber, value);
}
/// <summary>
/// 孔径
/// </summary>
public double Diameter
{
get => _diameter;
set => SetProperty(ref _diameter, value);
}
/// <summary>
/// 刀具类型显示文本
/// </summary>
public string ToolTypeDisplay
{
get => _toolTypeDisplay;
set => SetProperty(ref _toolTypeDisplay, value);
}
/// <summary>
/// 背景色
/// </summary>
public Brush BackgroundColor
{
get => _backgroundColor;
set => SetProperty(ref _backgroundColor, value);
}
public event PropertyChangedEventHandler? PropertyChanged;
protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value))
return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}
protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}

View File

@@ -0,0 +1,104 @@
<Window x:Class="DrillTools.ToolReorderConfirmationWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:DrillTools"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="刀序重排确认"
Width="800"
Height="600"
ResizeMode="NoResize"
WindowStartupLocation="CenterOwner"
mc:Ignorable="d">
<Window.Resources>
<!-- 未改动的背景色(浅绿色) -->
<SolidColorBrush x:Key="UnchangedBackground" Color="#E8F5E9"/>
<!-- 改动的背景色(浅红色) -->
<SolidColorBrush x:Key="ChangedBackground" Color="#FFEBEE"/>
</Window.Resources>
<Grid Margin="15">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- 标题和说明 -->
<StackPanel Grid.Row="0" Margin="0,0,0,15">
<TextBlock Text="刀序重排确认" FontSize="{StaticResource LargeFontSize}" FontWeight="Bold" Margin="0,0,0,5"/>
<TextBlock Text="以下显示了原始刀序和重排后的刀序对比,请确认是否应用更改。" FontSize="{StaticResource DefaultFontSize}"/>
<StackPanel Orientation="Horizontal" Margin="0,10,0,0">
<Rectangle Width="20" Height="20" Fill="{StaticResource UnchangedBackground}" Stroke="Gray" StrokeThickness="1" Margin="0,0,5,0"/>
<TextBlock Text="未改动" VerticalAlignment="Center" Margin="0,0,15,0"/>
<Rectangle Width="20" Height="20" Fill="{StaticResource ChangedBackground}" Stroke="Gray" StrokeThickness="1" Margin="0,0,5,0"/>
<TextBlock Text="已改动" VerticalAlignment="Center"/>
</StackPanel>
</StackPanel>
<!-- 刀序对比区域 -->
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<!-- 原始刀序 -->
<GroupBox Grid.Column="0" Header="原始刀序" Margin="0,0,5,0">
<ListView Name="OriginalToolsListView" ItemsSource="{Binding OriginalTools}" ScrollViewer.ScrollChanged="OriginalToolsListView_ScrollChanged">
<ListView.View>
<GridView>
<GridViewColumn Header="序号" Width="60" DisplayMemberBinding="{Binding Order}"/>
<GridViewColumn Header="刀具编号" Width="80" DisplayMemberBinding="{Binding ToolNumber, StringFormat=T{0:D2}}"/>
<GridViewColumn Header="孔径(mm)" Width="80" DisplayMemberBinding="{Binding Diameter, StringFormat=F3}"/>
<GridViewColumn Header="类型" Width="70" DisplayMemberBinding="{Binding ToolTypeDisplay}"/>
</GridView>
</ListView.View>
<ListView.ItemContainerStyle>
<Style BasedOn="{StaticResource {x:Type ListViewItem}}" TargetType="ListViewItem">
<Setter Property="Background" Value="{Binding BackgroundColor}"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
</GroupBox>
<!-- 重排后刀序 -->
<GroupBox Grid.Column="1" Header="重排后刀序" Margin="5,0,0,0">
<ListView Name="ReorderedToolsListView" ItemsSource="{Binding ReorderedTools}" ScrollViewer.ScrollChanged="ReorderedToolsListView_ScrollChanged">
<ListView.View>
<GridView>
<GridViewColumn Header="序号" Width="60" DisplayMemberBinding="{Binding Order}"/>
<GridViewColumn Header="刀具编号" Width="80" DisplayMemberBinding="{Binding ToolNumber, StringFormat=T{0:D2}}"/>
<GridViewColumn Header="孔径(mm)" Width="80" DisplayMemberBinding="{Binding Diameter, StringFormat=F3}"/>
<GridViewColumn Header="类型" Width="70" DisplayMemberBinding="{Binding ToolTypeDisplay}"/>
</GridView>
</ListView.View>
<ListView.ItemContainerStyle>
<Style BasedOn="{StaticResource {x:Type ListViewItem}}" TargetType="ListViewItem">
<Setter Property="Background" Value="{Binding BackgroundColor}"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
</GroupBox>
</Grid>
<!-- 按钮区域 -->
<StackPanel Grid.Row="2"
HorizontalAlignment="Right"
Orientation="Horizontal"
Margin="0,15,0,0">
<Button Width="80"
Height="30"
Content="取消"
IsCancel="True"
Margin="0,0,10,0"
Click="CancelButton_Click" />
<Button Width="80"
Height="30"
Content="确认"
IsDefault="True"
Click="ConfirmButton_Click" />
</StackPanel>
</Grid>
</Window>

View File

@@ -0,0 +1,151 @@
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace DrillTools
{
/// <summary>
/// ToolReorderConfirmationWindow.xaml 的交互逻辑
/// </summary>
public partial class ToolReorderConfirmationWindow : Window
{
/// <summary>
/// 是否确认重排
/// </summary>
public bool IsConfirmed { get; private set; }
/// <summary>
/// 构造函数
/// </summary>
public ToolReorderConfirmationWindow()
{
InitializeComponent();
DataContext = new ToolReorderConfirmationViewModel();
}
/// <summary>
/// 使用原始和重排后的刀具列表初始化窗口
/// </summary>
/// <param name="originalTools">原始刀具列表</param>
/// <param name="reorderedTools">重排后刀具列表</param>
public ToolReorderConfirmationWindow(IEnumerable<ToolItem> originalTools, IEnumerable<ToolItem> reorderedTools) : this()
{
if (DataContext is ToolReorderConfirmationViewModel viewModel)
{
viewModel.LoadTools(originalTools, reorderedTools);
}
}
/// <summary>
/// 确认按钮点击事件
/// </summary>
private void ConfirmButton_Click(object sender, RoutedEventArgs e)
{
IsConfirmed = true;
Close();
}
/// <summary>
/// 取消按钮点击事件
/// </summary>
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
IsConfirmed = false;
Close();
}
/// <summary>
/// 原始刀序列表滚动事件处理
/// </summary>
private void OriginalToolsListView_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
if (sender is System.Windows.Controls.ListView listView && e.VerticalChange != 0)
{
// 获取原始列表的滚动位置
var scrollViewer = GetScrollViewer(listView);
if (scrollViewer != null)
{
// 同步到重排后列表
var reorderedScrollViewer = GetScrollViewer(ReorderedToolsListView);
if (reorderedScrollViewer != null)
{
reorderedScrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset);
}
}
}
}
/// <summary>
/// 重排后刀序列表滚动事件处理
/// </summary>
private void ReorderedToolsListView_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
if (sender is System.Windows.Controls.ListView listView && e.VerticalChange != 0)
{
// 获取重排后列表的滚动位置
var scrollViewer = GetScrollViewer(listView);
if (scrollViewer != null)
{
// 同步到原始列表
var originalScrollViewer = GetScrollViewer(OriginalToolsListView);
if (originalScrollViewer != null)
{
originalScrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset);
}
}
}
}
/// <summary>
/// 获取ListView中的ScrollViewer控件
/// </summary>
/// <param name="listView">ListView控件</param>
/// <returns>ScrollViewer控件</returns>
private ScrollViewer GetScrollViewer(System.Windows.Controls.ListView listView)
{
if (listView == null)
return null;
// 使用VisualTreeHelper查找ScrollViewer
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(listView); i++)
{
var child = VisualTreeHelper.GetChild(listView, i);
if (child is ScrollViewer scrollViewer)
{
return scrollViewer;
}
// 递归查找子控件
var result = GetScrollViewerFromChild(child);
if (result != null)
return result;
}
return null;
}
/// <summary>
/// 从子控件中递归查找ScrollViewer
/// </summary>
/// <param name="parent">父控件</param>
/// <returns>ScrollViewer控件</returns>
private ScrollViewer GetScrollViewerFromChild(DependencyObject parent)
{
if (parent == null)
return null;
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is ScrollViewer scrollViewer)
{
return scrollViewer;
}
// 递归查找
var result = GetScrollViewerFromChild(child);
if (result != null)
return result;
}
return null;
}
}
}