简体   繁体   中英

How to pass value from Main WIndow textbox to other User Control?

Aim:

I am aiming to pass value from main window ie the log in screen to other User Control forms.

This is MainWindow.Xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void CloseButton_Click(object sender, RoutedEventArgs e)
    {
        this.Close();
    }


    private void btnLogin_Click(object sender, RoutedEventArgs e)
    {

        string connString = ConfigurationManager.ConnectionStrings["Technical_Application.Properties.Settings.ConnectionString"].ConnectionString;
        string query = "SELECT count(*) from users where username = '" + txtUsername.Text + "' and password = MD5('" + txtPassword.Password + "')";

        using (var conn = new MySqlConnection(connString))
        {
            conn.Open();
            using (var cmd = new MySqlCommand(query, conn))
            {
                int count = Convert.ToInt32(cmd.ExecuteScalar());
                if(count == 1)
                {
                    Dashboard dashboard = new Dashboard();
                    dashboard.Show();
                    this.Close();
                }
                else
                {
                    MessageBox.Show("Username or Password unvalid", "Login Error", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
            conn.Close();
        }
    }
}

It opens up the dashboard . I now have a ListViewMenu directed to specific User Control forms, and opens on the dashboard.

Code to open different user controls

   private void ListViewMenu_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        int index = ListViewMenu.SelectedIndex;
        MoveCursorMenu(index);

        switch (index)
        {
            case 0:
                GridPrincipal.Children.Clear();
                GridPrincipal.Children.Add(new UserControlMain());

                break;
            case 1:
                GridPrincipal.Children.Clear();
                GridPrincipal.Children.Add(new UserControl1());
                break;
            default:
                break;
        }

    }

Question:

From MainWindow the text box with name of txtUsername how can I transfer the text value to other UserControl windows?

Wouldnt it be easy to add a string property in your Dashboard class, and pass it into that - like:

Dashboard dashboard = new Dashboard();
dashboard.UserName = txtUsername.Text;

Then you can pass the same string value down to other controls. Of course, ideally, you would implement the MVVM pattern and use bindings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM