简体   繁体   中英

Disable button of MainWindow and return to the initial state of MainWindow when I click an "OK" button of a Second Window in WPF (.NET Core)

I have two Windows in a WPF Application. The first is the MainWindow while the second is a SecondaryWindow that fills with data the MainWindow.

Briefly I have a "Load" button in my MainWindow which is disabled and gets enabled only when a user browse a local file. When the 'Load' gets enabled, the user is asked to fill some credentials to load the data into a table in SQL server. When the user clicks 'OK' in the second window I want my MainWindow to return in its initial state.

MainWindow.xaml.cs file

using MaterialDesignThemes.Wpf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Data;
using System.IO;

namespace TestEnvironment
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    
    public static class StringExtensions
    {
        public static string Args(this string str, params object[] args)
        {
            return String.Format(str, args);
        }
    }

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

        // Functions - Methods

        public DataTable ConvertToDataTable(string filePath)
        {
            DataTable tbl = new DataTable();

            // Take the first 10 lines
            var lines = File.ReadLines(filePath).Take(10);

            // Split each line and create an integer sequence where each value 
            // is the number of the splitted elements
            // then get the max value present in this sequence
            var max = lines.Select(x => x.Split('\t').Length).Max();

            // First line contains headers
            string[] headers = lines.First().Split('\t');

            // Now create the table with the max number of columns present
            for (int col = 0; col < max; col++)
                tbl.Columns.Add(headers[col], typeof(string));

            //Use the Rows.Add method that accepts an object array
            foreach (string line in lines.Skip(1))
            {

                tbl.Rows.Add(line.Split('\t'));

            }

            //UTF-8 encoding

            /*var utf8 = Encoding.UTF8;

            foreach (string line in lines.Skip(1))
            {
                IEnumerable<string> utf8Values = line.Split('\t')
                    .Select(s => utf8.GetString(Encoding.Convert(Encoding.ASCII, utf8,
                        Encoding.ASCII.GetBytes(s))));
                tbl.Rows.Add(utf8Values);
            }*/

            /*foreach (DataRow dr in tbl.Rows)
            {

                Debug.WriteLine(dr["Nationality"]);

                string s = dr["Nationality"].ToString();

                byte[] bytes = Encoding.Default.GetBytes(s);
                dr["Nationality"] = Encoding.UTF8.GetString(bytes);

                Debug.WriteLine(dr["Nationality"]);
            }*/

            return tbl;
        }

        public static void WriteDataToFile(DataTable submittedDataTable, string submittedFilePath)
        {
            int i = 0;
            StreamWriter sw = null;

            sw = new StreamWriter(submittedFilePath, false);

            for (i = 0; i < submittedDataTable.Columns.Count - 1; i++)
            {

                sw.Write(submittedDataTable.Columns[i].ColumnName + ";");

            }
            sw.Write(submittedDataTable.Columns[i].ColumnName);
            sw.WriteLine();

            foreach (DataRow row in submittedDataTable.Rows)
            {
                object[] array = row.ItemArray;

                for (i = 0; i < array.Length - 1; i++)
                {
                    sw.Write(array[i].ToString() + ";");
                }
                sw.Write(array[i].ToString());
                sw.WriteLine();

            }

            sw.Close();
        }

        public static void SubmitData(string connectionString, string tablenametext)
        {
            using (SqlConnection sqlConnection = new SqlConnection(connectionString))
            {
                sqlConnection.Open();
                using (var command = sqlConnection.CreateCommand())
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.CommandText = "createselectedtableinDB";
                    command.Parameters.AddWithValue("@TableName", tablenametext);
                    command.ExecuteNonQuery();
                }
            }
        }

        public static string CreateConnectionString(string servernametext, string databasenametext)
        {
            string connectionstring = "Server={0};Database={1};Integrated Security=SSPI".Args(servernametext, databasenametext);

            return connectionstring;
        }

        // Object Interactions

        private void BrowseButton_Click(object sender, RoutedEventArgs e)
        {   

            // Create OpenFileDialog
            Microsoft.Win32.OpenFileDialog openFileDlg = new Microsoft.Win32.OpenFileDialog();

            // Launch OpenFileDialog by calling ShowDialog method
            Nullable<bool> result = openFileDlg.ShowDialog();
            // Get the selected file name and display in a TextBox.
            // Load content of file in a TextBlock
            if (result == true)
            {
                FileNameTextBox.Text = openFileDlg.FileName;
                TextBlock1.Text = "Created on: " + File.GetCreationTime(openFileDlg.FileName).ToString() +"\n";
                
                Debug.WriteLine(File.GetCreationTime(openFileDlg.FileName).ToString());
                
                var datatablematrix = ConvertToDataTable(filePath: openFileDlg.FileName);

                /*Debug.WriteLine(datatablematrix);

                WriteDataToFile(datatablematrix, @"C:\Users\spano\Desktop\ApplicationOption2\testdummy.txt");*/

                grid.DataContext = datatablematrix.DefaultView;

            }

            // Set filter for file extension and default file extension  
            openFileDlg.DefaultExt = ".txt";
            openFileDlg.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";

            Debug.WriteLine("Txt imported");

            // Set initial directory    
            openFileDlg.InitialDirectory = @"C:\Documents\";

            // Multiple selection with all file types    
            openFileDlg.Multiselect = true;

            BrowseButton.IsEnabled = true;
            LoadButton.IsEnabled = true;

            Debug.WriteLine("End!");

        }

        private void LoadButton_Click(object sender, RoutedEventArgs e)
        {
            TableNamePopupwindow popup = new TableNamePopupwindow();
            //ShowDialog means you can't focus the parent window, only the popup
            popup.ShowDialog(); //execution will block here in this method until the popup closes
            
            string resultTable = popup.TableNameValue;
            string resultServer = popup.ServerNameValue;
            string resultDatabase = popup.DatabaseNameValue;

            var connectionString = CreateConnectionString(resultServer, resultDatabase);

            SubmitData(connectionString, resultTable);

        }

        private void PowerButton_Click(object sender, RoutedEventArgs e)
        {
            App.Current.Shutdown();
        }

        private void MinimizeButton_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        private void TabablzControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
    }
}

TableNamePopupwindow.xaml.cs

using MaterialDesignThemes.Wpf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Data;
using System.IO;

namespace TestEnvironment
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>

    public partial class TableNamePopupwindow : Window

    {
        public string TableNameValue

        {
           get
            {
                if (TableName == null) return string.Empty;

                return TableName.Text;
            }
        }

        public string ServerNameValue

        {
            get
            {
                if (ServerName == null) return string.Empty;

                return ServerName.Text;
            }
        }

        public string DatabaseNameValue

        {
            get
            {
                if (DatabaseName == null) return string.Empty;

                return DatabaseName.Text;
            }
        }

        public TableNamePopupwindow()
        {
            InitializeComponent();
        }

        private void OnOk_Click(object sender, RoutedEventArgs e)
        {   
            //code I found here: https://stackoverflow.com/questions/46089017/wpf-passing-text-from-one-window-to-another-window
            MainWindow mainWindow = new MainWindow();
            mainWindow.Show();
            mainWindow.LoadButton.IsEnabled = false;
            this.Close();
        }
    }
}

As you can see above OnOK click I want the 'LoadButton' to be redisabled.

Screenshot of MainWindow (Initial state when user opens the app)

在此处输入图片说明

Screenshot of MainWindow (The user browse a file)

在此处输入图片说明

Screenshot of SecondWindow (when the user clicks the "Load" button)

在此处输入图片说明

What I want is when the user clicks the 'OK' button to close the second window the MainWindow to return in its initial state (the 1st screenshot attached). Based on the code of the second window, which I found on this SO question I managed to return in the initial state but also open a new MainWindow everytime I click the "OK" button.

Instead of opening a new instance of MainWindow in your OnOk_Click handler, you should modify the already existing and open instance.

You need to get a reference to it somehow. You may for example inject TableNamePopupwindow with a reference when you open it:

private readonly MainWindow _mainWindow;

public TableNamePopupwindow(MainWindow mainWindow)
{
    InitializeComponent();
    _mainWindow = mainWindow;
}

private void OnOk_Click(object sender, RoutedEventArgs e)
{
    _mainWindow.LoadButton.IsEnabled = false;
    this.Close();
}

MainWindow:

TableNamePopupwindow popup = new TableNamePopupwindow(this);
popup.ShowDialog();

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