WPF: Create a dialog / prompt

前端 未结 4 451
执念已碎
执念已碎 2020-12-12 13:42

I need to create a Dialog / Prompt including TextBox for user input. My problem is, how to get the text after having confirmed the dialog? Usually I would make a class for t

4条回答
  •  遥遥无期
    2020-12-12 14:08

    I just add a static method to call it like a MessageBox:

    
    
        
        
        
        
            

    And the code behind:

    public partial class PromptDialog : Window
    {
        public enum InputType
        {
            Text,
            Password
        }
    
        private InputType _inputType = InputType.Text;
    
        public PromptDialog(string question, string title, string defaultValue = "", InputType inputType = InputType.Text)
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(PromptDialog_Loaded);
            txtQuestion.Text = question;
            Title = title;
            txtResponse.Text = defaultValue;
            _inputType = inputType;
            if (_inputType == InputType.Password)
                txtResponse.Visibility = Visibility.Collapsed;
            else
                txtPasswordResponse.Visibility = Visibility.Collapsed;
        }
    
        void PromptDialog_Loaded(object sender, RoutedEventArgs e)
        {
            if (_inputType == InputType.Password)
                txtPasswordResponse.Focus();
            else
                txtResponse.Focus();
        }
    
        public static string Prompt(string question, string title, string defaultValue = "", InputType inputType = InputType.Text)
        {
            PromptDialog inst = new PromptDialog(question, title, defaultValue, inputType);
            inst.ShowDialog();
            if (inst.DialogResult == true)
                return inst.ResponseText;
            return null;
        }
    
        public string ResponseText
        {
            get
            {
                if (_inputType == InputType.Password)
                    return txtPasswordResponse.Password;
                else
                    return txtResponse.Text;
            }
        }
    
        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = true;
            Close();
        }
    
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }
    

    So you can call it like:

    string repeatPassword = PromptDialog.Prompt("Repeat password", "Password confirm", inputType: PromptDialog.InputType.Password);
    

提交回复
热议问题