WPF C# InputBox

前端 未结 6 870
予麋鹿
予麋鹿 2020-12-02 17:57

I am building a WPF application using C#. I want to pop out a dialog box to prompt the user to enter his/her name. After that I will keep track of the name and save some dat

6条回答
  •  情书的邮戳
    2020-12-02 18:10

    I prefer to take an approach using dialogs that doesn't lock up the application, and moves away from the more traditional Win32 Dialog.

    Example

    Input Dialog

    Input Dialog Hidden

    Input Dialog not showing.

    In this example I use a simplified version of the MVVM based solution I am using for my applications. It may not be pretty, but should give you a solid idea on the basics behind it.

    The XAML:

    
    
        
            

    It's very easy to show this dialog as you only need to set the Visibility of the InputBox grid to visible. You then simply handle the Yes / No buttons and get the Input text from the TextBox.

    So instead of using code that requires ShowDialog(), you simply set the Visibility option to Visible. There are still some things to do in this example that we will handle in code-behind, like for example clearing the InputText box after handling the Yes/No Button clicks.

    The code-behind:

    namespace WpfApplication1
    {
        /// 
        /// Interaction logic for MainWindow.xaml
        /// 
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }
    
            private void CoolButton_Click(object sender, RoutedEventArgs e)
            {
                // CoolButton Clicked! Let's show our InputBox.
                InputBox.Visibility = System.Windows.Visibility.Visible;
            }
    
            private void YesButton_Click(object sender, RoutedEventArgs e)
            {
                // YesButton Clicked! Let's hide our InputBox and handle the input text.
                InputBox.Visibility = System.Windows.Visibility.Collapsed;
    
                // Do something with the Input
                String input = InputTextBox.Text;
                MyListBox.Items.Add(input); // Add Input to our ListBox.
    
                // Clear InputBox.
                InputTextBox.Text = String.Empty;
            }
    
            private void NoButton_Click(object sender, RoutedEventArgs e)
            {
                // NoButton Clicked! Let's hide our InputBox.
                InputBox.Visibility = System.Windows.Visibility.Collapsed;
    
                // Clear InputBox.
                InputTextBox.Text = String.Empty;
            }
        }
    }
    

    The code-behind could easily be done using a Dependency, or as ViewModel logic in this case, but for simplicity I kept it in the code-behind.

提交回复
热议问题