XAML WPF C# InputBox

xxhby3vn  于 2023-08-01  发布在  C#
关注(0)|答案(6)|浏览(192)

我正在使用C#构建WPF应用程序。我想弹出一个对话框,提示用户输入他/她的名字。之后,我将跟踪该名称并使用该名称将一些数据保存到.txt文件中。

例如:

名称输入为
name =“John”
所以我有数据
data=“1,2,3”;
然后我将“数据”保存在John.txt文件中。
有人知道怎么做吗?

我觉得问题是如何弹出对话框让用户输入name。

alen0pnh

alen0pnh1#

我更喜欢采用一种使用对话框的方法,这种方法不会锁定应用程序,并且远离更传统的Win32对话框。

示例

x1c 0d1x的数据

输入对话框隐藏



在本例中,我使用了一个基于MVVM的解决方案的简化版本,我正在为我的应用程序使用这个解决方案。它可能不漂亮,但应该给予你一个坚实的想法背后的基础知识。

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>
</Window>

字符串
显示此对话框非常容易,因为您只需要将InputBox网格的可见性设置为可见。然后您只需处理Yes / No按钮并从TextBox中获取输入文本。
因此,无需使用需要ShowDialog()的代码,只需将Visibility选项设置为Visible。在这个例子中还有一些事情要做,我们将在代码隐藏中处理,例如在处理Yes/No Button点击后清除InputText框。

代码隐藏:

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;
        }
    }
}


代码隐藏可以很容易地使用Dependency来完成,或者在本例中作为ViewModel逻辑,但为了简单起见,我将其保留在代码隐藏中。

tkclm6bt

tkclm6bt2#

这是我的解决方案。它是完全可定制的。

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

字符串
或者,如果你愿意的话

string inputRead= new InputBox("Insert something", "Title", "Arial", 20).ShowDialog()


这是类的代码

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;
    }
}


希望能有所帮助。

ybzsozfc

ybzsozfc3#

只需在Visual Studio项目中创建另一个Window类,它将用户名保存在公共属性中。然后在主窗口的某处创建此窗口的示例,并使用ShowDialog方法显示它。这将阻止直到您的“对话框”窗口关闭。然后你就可以从公共属性中获取用户名,并对它做任何你想做的事情。

snvhrwxg

snvhrwxg4#

在您的项目中创建/添加一个新的Window,以获取用户的输入。然后可以使用Window.ShowWindow.ShowDialog将该窗口显示为弹出窗口
另外,在创建的窗口中添加一个OK按钮,然后单击OK按钮,将信息保存在文本文件中

apeeds0o

apeeds0o5#

MSDN上的自定义对话框部分可能会给予您一些指导:WPF中的自定义对话框。还有代码示例和XAML源代码。
一旦你处理了这个问题,你可以搜索如何将数据保存到文件中-这是相当容易的,并且有很多方法可以做到这一点(其中之一是使用TextWriter类:example)。

brtdzjyr

brtdzjyr6#

谢谢!!我的修改版本:

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;
    }
}

字符串

相关问题