如何在WPF中实现带确认取消功能的WinForms风格输入弹窗
WPF 输入窗口实现方案
1. 创建WPF窗口(XAML布局)
新建一个WPF窗口(命名为InputWindow),编写以下XAML代码实现输入框和按钮布局:
<Window x:Class="YourNamespace.InputWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Input" Height="150" Width="350" ResizeMode="NoResize" WindowStartupLocation="CenterOwner" PreviewKeyDown="Window_PreviewKeyDown"> <Grid Margin="10"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto" Margin="0,10,0,0"/> </Grid.RowDefinitions> <!-- 用户输入文本框 --> <TextBox x:Name="InputTextBox" Grid.Row="0" /> <!-- 确认/取消按钮容器 --> <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right"> <Button x:Name="ConfirmBtn" Content="确认" Width="80" Margin="0,0,10,0" Click="ConfirmBtn_Click"/> <Button x:Name="CancelBtn" Content="取消" Width="80" Click="CancelBtn_Click"/> </StackPanel> </Grid> </Window>
2. 后台C#逻辑实现
在窗口的后台代码中,实现静态调用方法、结果返回和快捷键处理:
using System.Windows; namespace YourNamespace { public partial class InputWindow : Window { // 存储用户输入内容的属性 public string InputContent { get; private set; } private InputWindow(string title) { InitializeComponent(); this.Title = title; // 窗口打开时自动聚焦输入框 InputTextBox.Focus(); } /// <summary> /// 静态调用方法,模拟WinForms弹窗调用逻辑 /// </summary> /// <param name="title">窗口标题</param> /// <param name="inputContent">输出参数,返回用户输入内容</param> /// <returns>点击确认返回true,取消返回false</returns> public static bool Show(string title, out string inputContent) { inputContent = string.Empty; var window = new InputWindow(title); var dialogResult = window.ShowDialog(); if (dialogResult == true) { inputContent = window.InputContent; return true; } return false; } // 确认按钮点击事件 private void ConfirmBtn_Click(object sender, RoutedEventArgs e) { InputContent = InputTextBox.Text; this.DialogResult = true; this.Close(); } // 取消按钮点击事件 private void CancelBtn_Click(object sender, RoutedEventArgs e) { this.DialogResult = false; this.Close(); } // 快捷键处理:回车触发确认,ESC触发取消 private void Window_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e) { if (e.Key == System.Windows.Input.Key.Enter) { ConfirmBtn_Click(sender, e); e.Handled = true; } else if (e.Key == System.Windows.Input.Key.Escape) { CancelBtn_Click(sender, e); e.Handled = true; } } } }
3. 调用方式
按照你期望的逻辑调用窗口,通过out参数获取用户输入内容:
string foo; if (InputWindow.Show("abc", out foo)) { // 用户点击确认,foo即为输入内容 MessageBox.Show($"输入内容:{foo}"); } else { // 用户点击取消 MessageBox.Show("已取消输入"); }
额外说明
- 窗口以模态方式打开,阻塞父线程直到窗口关闭
- 启动时自动聚焦输入框,优化操作流程
- 限制窗口不可调整大小,保持和WinForms弹窗一致的简洁风格
内容的提问来源于stack exchange,提问作者Laurin Theisen
相关产品推荐
相关产品推荐

