NavisworksTransport/.agents/skills/project-tools/utils/DialogHelper.md

128 lines
2.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# DialogHelper 使用指南
## 文件位置
`src/Utils/DialogHelper.cs`
## 用途
统一处理对话框的 Owner 设置和置顶显示,解决 Navisworks 插件环境中的窗口焦点问题。
## 核心方法
### 1. SetOwnerSafely - 安全设置Owner推荐
```csharp
// 场景:在 ViewModel 中创建对话框
var dialog = new MyDialog();
DialogHelper.SetOwnerSafely(dialog);
dialog.Show(); // 或 dialog.ShowDialog();
```
**特点**
- 自动查找可用的 Owner 窗口
- 处理 Navisworks 插件环境的特殊情况
- 捕获异常,不会导致程序崩溃
### 2. ShowDialog - 显示模态对话框(完整处理)
```csharp
// 场景:显示需要返回结果的模态对话框
var dialog = new MyInputDialog();
bool? result = DialogHelper.ShowDialog(dialog);
```
### 3. ShowMessageBox - 显示消息框
```csharp
// 场景:显示错误提示或确认对话框
DialogHelper.ShowMessageBox(
"操作成功完成",
"提示",
MessageBoxButton.OK,
MessageBoxImage.Information
);
```
### 4. SetWin32Owner - 强制置顶到Navisworks主窗口
```csharp
// 场景对话框必须置顶到Navisworks主窗口极少数情况
var dialog = new MyDialog();
DialogHelper.SetWin32Owner(dialog);
dialog.Show();
```
## 使用示例
### 示例1ViewModel中显示非模态对话框
```csharp
private MyDialog _myDialog;
private void ShowMyDialog()
{
if (_myDialog != null && _myDialog.IsVisible)
{
_myDialog.Activate();
return;
}
_myDialog = new MyDialog();
DialogHelper.SetOwnerSafely(_myDialog); // ✅ 使用工具方法
_myDialog.Show();
_myDialog.Closed += (s, e) => _myDialog = null;
}
```
### 示例2显示确认对话框
```csharp
private bool ConfirmDelete()
{
var result = DialogHelper.ShowMessageBox(
"确定要删除此路径吗?",
"确认删除",
MessageBoxButton.YesNo,
MessageBoxImage.Warning
);
return result == MessageBoxResult.Yes;
}
```
## 注意事项
1. **不要在构造函数中设置 Owner**
```csharp
// ❌ 错误
public MyDialog()
{
InitializeComponent();
this.Owner = Application.Current.MainWindow; // 可能抛出异常
}
// ✅ 正确:在外部设置
var dialog = new MyDialog();
DialogHelper.SetOwnerSafely(dialog);
```
2. **非模态对话框也需要设置 Owner**
```csharp
// 即使是 Show() 而非 ShowDialog(),也需要设置 Owner
var dialog = new MyDialog();
DialogHelper.SetOwnerSafely(dialog); // 确保正确置顶
dialog.Show();
```
3. **XAML 中不要设置 Owner**
```xml
<!-- ❌ 错误 -->
<Window ...
Owner="{x:Static Application.Current.MainWindow}">
<!-- ✅ 正确XAML中不设置代码中设置 -->
<Window ...>
```