web-dev-qa-db-fra.com

WPF C # InputBox

Je fais une application WPF en utilisant C #. Je souhaite faire apparaître une boîte de dialogue pour inviter l'utilisateur à saisir son nom. Après cela, je garderai une trace du nom et enregistrerai des données dans un fichier txt en utilisant le nom.

Par exemple,

La saisie du nom est name = "John"

Et j'ai donc une donnée data = "1, 2, 3";

puis j'enregistre les "données" dans le fichier John.txt.

Quelqu'un sait comment le faire? Je pense que le problème est de savoir comment faire apparaître une boîte de dialogue pour que l'utilisateur saisisse son nom.

Je vous remercie!

18
user981924

Je préfère adopter une approche utilisant des boîtes de dialogue qui ne verrouillent pas l'application et s'éloigne de la boîte de dialogue Win32 plus traditionnelle.

Exemple

Input Dialog

Boîte de dialogue d'entrée masquée

Input Dialog not showing.

Dans cet exemple, j'utilise une version simplifiée de la solution basée sur MVVM que j'utilise pour mes applications. Ce n'est peut-être pas joli, mais cela devrait vous donner une idée solide des principes de base.

Le XAML:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.Microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.Microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <StackPanel>
        <Button Content="Cool Button" x:Name="CoolButton" Click="CoolButton_Click"/>
        <ListBox x:Name="MyListBox"/>
    </StackPanel>

    <!-- It's important that this is in the end of the XAML as it needs to be on top of everything else! -->
    <Grid x:Name="InputBox" Visibility="Collapsed">
        <Grid Background="Black" Opacity="0.5"/>
        <Border
            MinWidth="250"
            Background="Orange" 
            BorderBrush="Black" 
            BorderThickness="1" 
            CornerRadius="0,55,0,55" 
            HorizontalAlignment="Center" 
            VerticalAlignment="Center">
            <StackPanel>
                <TextBlock Margin="5" Text="Input Box:" FontWeight="Bold" FontFamily="Cambria" />
                <TextBox MinWidth="150" HorizontalAlignment="Center" VerticalAlignment="Center" x:Name="InputTextBox"/>
                <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
                    <Button x:Name="YesButton" Margin="5" Content="Yes" Background="{x:Null}" Click="YesButton_Click"/>
                    <Button x:Name="NoButton" Margin="5" Content="No" Background="{x:Null}" Click="NoButton_Click" />
                </StackPanel>
            </StackPanel>
        </Border>
    </Grid>
</Grid>

Il est très facile d'afficher cette boîte de dialogue car il vous suffit de définir la visibilité de la grille InputBox sur visible. Vous manipulez alors simplement les boutons Oui/Non et obtenez le texte d'entrée de la TextBox.

Ainsi, au lieu d'utiliser du code qui nécessite ShowDialog(), vous définissez simplement l'option Visibility sur Visible. Il y a encore des choses à faire dans cet exemple que nous traiterons en code-behind, comme par exemple effacer la zone InputText après avoir géré les clics sur le bouton Oui/Non.

Le code-behind:

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    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;
        }
    }
}

Le code-behind pourrait facilement être fait en utilisant une dépendance, ou comme logique ViewModel dans ce cas, mais pour plus de simplicité, je l'ai gardé dans le code-behind.

34
eandersson

Voici ma solution, j'ai mis environ 3 heures pour la taper. Il est entièrement personnalisable.

string var = new InputBox("text").ShowDialog();

Et c'est le code de la classe

public class InputBox
{

    Window Box = new Window();//window for the inputbox
    FontFamily font = new FontFamily("Tahoma");//font for the whole inputbox
    int FontSize=30;//fontsize for the input
    StackPanel sp1=new StackPanel();// items container
    string title = "InputBox";//title as heading
    string boxcontent;//title
    string defaulttext = "Write here your name...";//default textbox content
    string errormessage = "Invalid answer";//error messagebox content
    string errortitle="Error";//error messagebox heading title
    string okbuttontext = "OK";//Ok button content
    Brush BoxBackgroundColor = Brushes.GreenYellow;// Window Background
    Brush InputBackgroundColor = Brushes.Ivory;// Textbox Background
    bool clicked = false;
    TextBox input = new TextBox();
    Button ok = new Button();
    bool inputreset = false;

    public InputBox(string content)
    {
        try
        {
            boxcontent = content;
        }
        catch { boxcontent = "Error!"; }
        windowdef();
    }

    public InputBox(string content,string Htitle, string DefaultText)
    {
        try
        {
            boxcontent = content;
        }
        catch { boxcontent = "Error!"; }
        try
        {
            title = Htitle;
        }
        catch 
        {
            title = "Error!";
        }
        try
        {
            defaulttext = DefaultText;
        }
        catch
        {
            DefaultText = "Error!";
        }
        windowdef();
    }

    public InputBox(string content, string Htitle,string Font,int Fontsize)
    {
        try
        {
            boxcontent = content;
        }
        catch { boxcontent = "Error!"; }
        try
        {
            font = new FontFamily(Font);
        }
        catch { font = new FontFamily("Tahoma"); }
        try
        {
            title = Htitle;
        }
        catch
        {
            title = "Error!";
        }
        if (Fontsize >= 1)
            FontSize = Fontsize;
        windowdef();
    }

    private void windowdef()// window building - check only for window size
    {
        Box.Height = 500;// Box Height
        Box.Width = 300;// Box Width
        Box.Background = BoxBackgroundColor;
        Box.Title = title;
        Box.Content = sp1;
        Box.Closing += Box_Closing;
        TextBlock content=new TextBlock();
        content.TextWrapping = TextWrapping.Wrap;
        content.Background = null;
        content.HorizontalAlignment = HorizontalAlignment.Center;
        content.Text = boxcontent;
        content.FontFamily = font;
        content.FontSize = FontSize;
        sp1.Children.Add(content);

        input.Background = InputBackgroundColor;
        input.FontFamily = font;
        input.FontSize = FontSize;
        input.HorizontalAlignment = HorizontalAlignment.Center;
        input.Text = defaulttext;
        input.MinWidth = 200;
        input.MouseEnter += input_MouseDown;
        sp1.Children.Add(input);
        ok.Width=70;
        ok.Height=30;
        ok.Click += ok_Click;
        ok.Content = okbuttontext;
        ok.HorizontalAlignment = HorizontalAlignment.Center;
        sp1.Children.Add(ok);

    }

    void Box_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        if(!clicked)
        e.Cancel = true;
    }

    private void input_MouseDown(object sender, MouseEventArgs e)
    {
        if ((sender as TextBox).Text == defaulttext && inputreset==false)
        {
            (sender as TextBox).Text = null;
            inputreset = true;
        }
    }

    void ok_Click(object sender, RoutedEventArgs e)
    {
        clicked = true;
        if (input.Text == defaulttext||input.Text == "")
            MessageBox.Show(errormessage,errortitle);
        else
        {
            Box.Close();
        }
        clicked = false;
    }

    public string ShowDialog()
    {
        Box.ShowDialog();
        return input.Text;
    }
}

J'espère que cela peut être utile.

7
Moreno G

Créez simplement une autre classe Window dans votre projet Visual Studio, qui contient le nom d'utilisateur dans une propriété publique. Créez ensuite une instance de cette fenêtre quelque part dans votre fenêtre principale et affichez-la à l'aide de la méthode ShowDialog. Cela se bloque jusqu'à la fermeture de votre fenêtre de "dialogue". Ensuite, vous pouvez obtenir le nom d'utilisateur de la propriété publique et faire ce que vous voulez avec.

4
Vertigo

Créez/ajoutez un nouveau Window dans votre projet pour recevoir les commentaires de l'utilisateur. Vous pouvez ensuite utiliser Window.Show ou Window.ShowDialog pour afficher cette fenêtre sous forme de fenêtre contextuelle

Ajoutez également un bouton OK n fenêtre créée et sur le bouton OK cliquez sur enregistrer les informations dans le fichier texte

3
Haris Hasan

La section sur les boîtes de dialogue personnalisées sur MSDN peut vous donner quelques conseils: boîte de dialogue personnalisée dans WPF . Il y a aussi un exemple de code et une source XAML.

Une fois que vous avez traité cela, vous pouvez rechercher comment enregistrer des données dans un fichier - c'est assez facile, et il existe une multitude de façons de le faire (dont l'une utilise TextWriter class: example =).

2
k.m

Je vous remercie!! Ma version modifiée:

public class InputBox
{
    Window Box = new Window();//window for the inputbox
    FontFamily font = new FontFamily("Avenir");//font for the whole inputbox
    int FontSize = 14;//fontsize for the input
    StackPanel sp1 = new StackPanel();// items container
    string title = "Dica s.l.";//title as heading
    string boxcontent;//title
    string defaulttext = "";//default textbox content
    string errormessage = "Datos no válidos";//error messagebox content
    string errortitle = "Error";//error messagebox heading title
    string okbuttontext = "OK";//Ok button content
    string CancelButtonText = "Cancelar";
    Brush BoxBackgroundColor = Brushes.WhiteSmoke;// Window Background
    Brush InputBackgroundColor = Brushes.Ivory;// Textbox Background
    bool clickedOk = false;
    TextBox input = new TextBox();
    Button ok = new Button();
    Button cancel = new Button();
    bool inputreset = false;


    public InputBox(string content)
    {
        try
        {
            boxcontent = content;
        }
        catch { boxcontent = "Error!"; }
        windowdef();
    }

    public InputBox(string content, string Htitle, string DefaultText)
    {
        try
        {
            boxcontent = content;
        }
        catch { boxcontent = "Error!"; }
        try
        {
            title = Htitle;
        }
        catch
        {
            title = "Error!";
        }
        try
        {
            defaulttext = DefaultText;
        }
        catch
        {
            DefaultText = "Error!";
        }
        windowdef();
    }

    public InputBox(string content, string Htitle, string Font, int Fontsize)
    {
        try
        {
            boxcontent = content;
        }
        catch { boxcontent = "Error!"; }
        try
        {
            font = new FontFamily(Font);
        }
        catch { font = new FontFamily("Tahoma"); }
        try
        {
            title = Htitle;
        }
        catch
        {
            title = "Error!";
        }
        if (Fontsize >= 1)
            FontSize = Fontsize;
        windowdef();
    }

    private void windowdef()// window building - check only for window size
    {
        Box.Height = 100;// Box Height
        Box.Width = 450;// Box Width
        Box.Background = BoxBackgroundColor;
        Box.Title = title;
        Box.Content = sp1;
        Box.Closing += Box_Closing;
        Box.WindowStyle = WindowStyle.None;
        Box.WindowStartupLocation = WindowStartupLocation.CenterScreen;

        TextBlock content = new TextBlock();
        content.TextWrapping = TextWrapping.Wrap;
        content.Background = null;
        content.HorizontalAlignment = HorizontalAlignment.Center;
        content.Text = boxcontent;
        content.FontFamily = font;
        content.FontSize = FontSize;
        sp1.Children.Add(content);

        input.Background = InputBackgroundColor;
        input.FontFamily = font;
        input.FontSize = FontSize;
        input.HorizontalAlignment = HorizontalAlignment.Center;
        input.Text = defaulttext;
        input.MinWidth = 200;
        input.MouseEnter += input_MouseDown;
        input.KeyDown += input_KeyDown;

        sp1.Children.Add(input);

        ok.Width = 70;
        ok.Height = 30;
        ok.Click += ok_Click;
        ok.Content = okbuttontext;

        cancel.Width = 70;
        cancel.Height = 30;
        cancel.Click += cancel_Click;
        cancel.Content = CancelButtonText;

        WrapPanel gboxContent = new WrapPanel();
        gboxContent.HorizontalAlignment = HorizontalAlignment.Center;

        sp1.Children.Add(gboxContent);
        gboxContent.Children.Add(ok);
        gboxContent.Children.Add(cancel);

        input.Focus();
    }

    void Box_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
       //validation
    }

    private void input_MouseDown(object sender, MouseEventArgs e)
    {
        if ((sender as TextBox).Text == defaulttext && inputreset == false)
        {
            (sender as TextBox).Text = null;
            inputreset = true;
        }
    }

    private void input_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter && clickedOk == false )
        {
            e.Handled = true;
            ok_Click(input, null);
        }

        if (e.Key == Key.Escape)
        {
            cancel_Click(input, null);
        }
    }

    void ok_Click(object sender, RoutedEventArgs e)
    {
        clickedOk = true;
        if (input.Text == defaulttext || input.Text == "")
            MessageBox.Show(errormessage, errortitle,MessageBoxButton.OK,MessageBoxImage.Error);
        else
        {
            Box.Close();
        }
        clickedOk = false;
    }

    void cancel_Click(object sender, RoutedEventArgs e)
    {
        Box.Close();
    }

    public string ShowDialog()
    {
        Box.ShowDialog();
        return input.Text;
    }
}
0
AlMuz