private void ChooseFileAutoSuggestBox_TextChanged(object sender, TextChangedEventArgs e) { var filePath = ((AutoSuggestBox)sender).Text; var filePathExtension = Path.GetExtension(filePath); if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath)) { if (filePathExtension == ".xlsx" || filePathExtension == ".xls") { var uiMessageBox = new MessageBox { Title = "请确认打开信息!", Content = $"你是否想打开以下路径的Excel文件{filePath}?", }; uiMessageBox.ButtonLeftClick += (sender, args) => { uiMessageBox.Close(); ChooseFileAutoSuggestBox_MouseDoubleClick(sender, args); }; uiMessageBox.ButtonLeftName = "重选"; uiMessageBox.ButtonRightClick += (sender, args) => { uiMessageBox.Close(); ExcelToDataTableToDBAndDataGrid(); }; uiMessageBox.ButtonRightName = "确认"; uiMessageBox.Show(); } else { var uiMessageBox = new MessageBox { Title = "打开错误!", Content = "该文件非Excel文件!", }; uiMessageBox.ButtonLeftClick += (sender, args) => { uiMessageBox.Close(); ChooseFileAutoSuggestBox_MouseDoubleClick(sender, args); }; uiMessageBox.ButtonLeftName = "重选"; uiMessageBox.ButtonRightClick += (sender, args) => { uiMessageBox.Close(); }; uiMessageBox.ButtonRightName = "关闭"; uiMessageBox.Show(); } } else { var uiMessageBox = new MessageBox { Title = "打开错误!", Content = "该文件不存在!", }; uiMessageBox.ButtonLeftClick += (sender, args) => { uiMessageBox.Close(); ChooseFileAutoSuggestBox_MouseDoubleClick(sender, args); }; uiMessageBox.ButtonLeftName = "重选"; uiMessageBox.ButtonRightClick += (sender, args) => { uiMessageBox.Close(); }; uiMessageBox.ButtonRightName = "关闭"; uiMessageBox.Show(); } }请优化上述代码
时间: 2024-01-09 14:04:44 浏览: 89
可以考虑将重复的代码封装成一个方法,减少代码冗余,并且可以提高可读性和可维护性。另外,可以使用枚举类型或常量来代替硬编码的字符串,增加代码的可读性和可维护性。
以下是一个示例代码:
```
private void OpenExcelFile(string filePath)
{
var filePathExtension = Path.GetExtension(filePath);
if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
{
ShowMessageBox("打开错误!", "该文件不存在!", MessageBoxButton.OK);
}
else if (filePathExtension != ".xlsx" && filePathExtension != ".xls")
{
ShowMessageBox("打开错误!", "该文件非Excel文件!", MessageBoxButton.OK);
}
else
{
var messageBoxResult = ShowMessageBox("请确认打开信息!", $"你是否想打开以下路径的Excel文件{filePath}?", MessageBoxButton.YesNo);
if (messageBoxResult == MessageBoxResult.Yes)
{
ChooseFileAutoSuggestBox_MouseDoubleClick(sender, args);
}
}
}
private MessageBoxResult ShowMessageBox(string title, string content, MessageBoxButton button)
{
var uiMessageBox = new MessageBox { Title = title, Content = content };
uiMessageBox.ButtonLeftName = "重选";
uiMessageBox.ButtonLeftClick += (sender, args) => { uiMessageBox.Close(); ChooseFileAutoSuggestBox_MouseDoubleClick(sender, args); };
uiMessageBox.ButtonRightName = button == MessageBoxButton.OK ? "关闭" : "确认";
uiMessageBox.ButtonRightClick += (sender, args) => { uiMessageBox.Close(); };
uiMessageBox.Show();
return uiMessageBox.Result;
}
private void ChooseFileAutoSuggestBox_TextChanged(object sender, TextChangedEventArgs e)
{
var filePath = ((AutoSuggestBox)sender).Text;
OpenExcelFile(filePath);
}
```
阅读全文