0

In my project (WPF) there is a form (in which an object is declared) that includes a frame that shows different pages according to the button that is clicked. In a page I drag a file and I get the path. How can I return the path to the main form so I can "send" it to the object? (Which will then be used by other functions within the form)

(Partial) code of Main form

    CSV csv = new CSV();
    public MainWindow()
    {
        InitializeComponent();
        Main.Content = new LoadCSVPage();
    }
    public MainWindow(string path)
    {
        InitializeComponent();
        csv.SetLocation(path);
    }

Code of LoadCSV Page

public LoadCSVPage()
    {
        InitializeComponent();
    }
    private void LoadCSV_DragEnter(object sender, DragEventArgs e)
    {
        string filePath = "";
        string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
        foreach (string file in files)
        {
            filePath = file;
        }
        MainWindow main = new MainWindow(filePath);
        main.Show();
    }

I understood what was missing! After passing the variable to the main constructor, I did not display it (via the main.show). Now that I've inserted it, it does not convince me much. Is there a cleaner way to do it? Oh no, there's a problem. With the main.show an additional window is created!

1 Answers1

0

I start saying that there are a lot of ways to achieve what you want. The first problem i see (even if you didn't posted the XAML part of the project) is that you are showing MainWindow two times: the first when you show it, the second when you drag the file inside the page.

An idea could be passing Csv object to the page:

public CSV csv = new CSV();
public MainWindow()
{
    InitializeComponent();
    Main.Content = new LoadCSVPage(csv);
}

public partial class LoadCSVPage: Page
{
    private CSV _csv;

    public LoadCSVPage(CSV mainCsv)
    {
        InitializeComponent();
        _csv = mainCsv;
    }
    private void LoadCSV_DragEnter(object sender, DragEventArgs e)
    {
        string filePath = "";
        string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
        //foreach (string file in files)
        //{
            //This also is not really clear: what happen if you drag more then one file? 
            //This way you are cycling for each file, but you are selecting the last` 
            //filePath = file;
        //}
       if(files.Length > 0)
       {
           filePath = files.Last();
       }
       // Here the csv object can obtain the filePath
       _csv.SetLocation(filePath);

    }
}

And then you can pass the path directly from the method of the page.

Babbillumpa
  • 1,854
  • 1
  • 16
  • 21