WPF: Create a dialog / prompt

前端 未结 4 449
执念已碎
执念已碎 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:11

    Great answer of Josh, all credit to him, I slightly modified it to this however:

    MyDialog Xaml

        
            
            
            
                
                    
                    
                
                

    MyDialog Code Behind

        public MyDialog()
        {
            InitializeComponent();
        }
    
        public MyDialog(string title,string input)
        {
            InitializeComponent();
            TitleText = title;
            InputText = input;
        }
    
        public string TitleText
        {
            get { return TitleTextBox.Text; }
            set { TitleTextBox.Text = value; }
        }
    
        public string InputText
        {
            get { return InputTextBox.Text; }
            set { InputTextBox.Text = value; }
        }
    
        public bool Canceled { get; set; }
    
        private void BtnCancel_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Canceled = true;
            Close();
        }
    
        private void BtnOk_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Canceled = false;
            Close();
        }
    

    And call it somewhere else

    var dialog = new MyDialog("test", "hello");
    dialog.Show();
    dialog.Closing += (sender,e) =>
    {
        var d = sender as MyDialog;
        if(!d.Canceled)
            MessageBox.Show(d.InputText);
    }
    

提交回复
热议问题