Search code examples
c#labelmauiwinui-3winui

update label text through MainPage Helper class


To simplify my scenario, I have a label and a button in a MAUI application. And I want to update the label text through mainpagehelper class instead of mainpage class.

MainPage.xaml:

<Button
    x:Name="OrganizeBtn"
    Text="Organize"
    IsEnabled="False"
    Clicked="OnOrganizeClicked"
    HorizontalOptions="Center" />

<Label x:Name="completionMsg"
    FontSize="32"
    HorizontalOptions="Center" />

MainPage.xaml.cs:

private void OnOrganizeClicked(object sender, EventArgs e)
    {
        completionMsg.Text = "";
        MainPageHelper mh = new FileManager();
        int fileCount = mh.OrganizeFiles(folderPath.Text);
        completionMsg.Text = "Moved " + fileCount + " files!";
    }

public void UpdateCompletionText(string text)
    {
        completionMsg.Text = "Moving " + text + "...";
    }

MainPageHelper.cs:

public int OrganizeFiles(string folderToOrganize)
        {
            foreach (string folder in listOfFolders)
            {
                Directory.CreateDirectory(folderToOrganize + "\\" + folder);
                MainPage mp = new MainPage();
                mp.UpdateCompletionText(currentFile);  <--- want to update the label here
            }
        }

Here, when I debugged by keeping the breakpoint, the call is going to the UpdateCompletionText function in MainPage. But the text is not updating.

How can I get this working?


Solution

  • If the helper is to be able to update the page, it needs a reference to the page instance.

    You could inject it with one:

    MainPageHelper.cs:

    private MainPage _mainPage;
    
    //constructor:
    public MainPageHelper(MainPage mainPage)
    {
        _mainPage = mainPage;
    }
    
    public int OrganizeFiles(string folderToOrganize)
    {
        foreach (string folder in listOfFolders)
        {
            Directory.CreateDirectory(folderToOrganize + "\\" + folder);
            _mainPage.UpdateCompletionText(currentFile);
        }
    }
    

    MainPage.xaml.cs:

    private void OnOrganizeClicked(object sender, EventArgs e)
    {
        completionMsg.Text = "";
        MainPageHelper mh = new MainPageHelper(this);
        int fileCount = mh.OrganizeFiles(folderPath.Text);
        completionMsg.Text = "Moved " + fileCount + " files!";
    }