using System; using System.Windows; using XP.Common.GeneralForm.ViewModels; using XP.Common.Localization; namespace XP.Common.GeneralForm.Views { /// /// 通用输入对话框,支持单行文本输入和可选的输入验证 /// General input dialog with single-line text input and optional validation /// public partial class InputDialog : Window { private readonly InputDialogViewModel _viewModel; /// /// 用户输入的结果,取消时为 null | User input result, null if cancelled /// public string? Result { get; private set; } /// /// 构造函数 | Constructor /// /// 提示文本 | Prompt text /// 窗口标题 | Window title /// 默认值 | Default value /// 可选的验证委托,返回 null 表示通过,返回错误信息则阻止确认 | Optional validation delegate public InputDialog( string prompt, string title, string defaultValue = "", Func? validate = null) { _viewModel = new InputDialogViewModel(prompt, title, defaultValue, validate); DataContext = _viewModel; InitializeComponent(); // 继承调用方窗口图标 | Inherit caller window icon if (Application.Current?.MainWindow != null) { Icon = Application.Current.MainWindow.Icon; } } /// /// 确定按钮点击事件 | OK button click handler /// private void OnOkClick(object sender, RoutedEventArgs e) { // 执行验证 | Run validation if (!_viewModel.Validate()) return; Result = _viewModel.InputText; DialogResult = true; } /// /// 取消按钮点击事件 | Cancel button click handler /// private void OnCancelClick(object sender, RoutedEventArgs e) { Result = null; DialogResult = false; } /// /// 静态便捷方法,显示输入对话框并返回结果 | Static convenience method /// /// 提示文本 | Prompt text /// 窗口标题 | Window title /// 默认值 | Default value /// 可选的验证委托 | Optional validation delegate /// 父窗口(可选)| Owner window (optional) /// 用户输入的值,取消时返回 null | User input, null if cancelled public static string? Show( string prompt, string title, string defaultValue = "", Func? validate = null, Window? owner = null) { var dialog = new InputDialog(prompt, title, defaultValue, validate); // owner 未指定时自动回退到主窗口,确保对话框有父窗口约束不会被遮挡 // Fall back to MainWindow if owner not specified, ensuring dialog stays in front dialog.Owner = owner ?? Application.Current?.MainWindow; dialog.ShowDialog(); return dialog.Result; } } }