Search code examples
c#winui-3winui

Setting a ToggleSwitch on/off dynamically when the window loads


I have a ToggleSwitch defined in my XAML.

<ToggleSwitch x:Name="enable_toggle_button" Header="Turn on/off" OffContent="Disabled" OnContent="Enabled" IsOn="False" Toggled="ToggleSwitch_Toggled"/>

When my application loads up, I want to perform a check on my application. If my application is doing something, I want to auto set the toggle switch to on. If my app isn't doing something, I want it to set the toggle to off. Simple...

Inside the .cs constructor of my window, I have the following:

public home_page()
{
    this.InitializeComponent();

    Task.Run(() => { set_enabled_disabled_switch(); });
}

Set_enabled_disabled_switch() then looks like this:

 private async Task set_enabled_disabled_switch()
 {
     bool is_it_running = await Ipc_handler.send_is_my_app_running_message() ;  // Under the covers, this send an IPC pipe message to a back end component, that then returns to tell my GUI app if its running or not.  it returns a true or false boolean. 

     if (is_it_running)
     {
         Trace.WriteLine("GUI:app is on, so enabling toggle switch", "info");
         enable_toggle_button.IsOn = true;
     }
     else
     {
         Trace.WriteLine("GUI: App is off, so disabling toggle switch", "info");
         enable_toggle_button.IsOn = false;
     }
 }

In my debug output, my Trace.Writelines are printing the right thing. But the enable_toggle_button.IsOn = true or false doesn't seem to be working. The Toggle switch in the GUI isn't changing accordingly.

Any ideas what I'm doing wrong?


Solution

  • You need to be on the main (UI) thread to access the UI. You can check if you are on the main thread with the Threads Window.

    For example:

    Main Thread

    Instead of calling a Task inside the constructor, try using the Loaded event, which will be running on the main thread.

    public home_page()
    {
        InitializeComponent();
        Loaded += home_page_Loaded;
    }
    
    private async void home_page_Loaded(object sender, RoutedEventArgs e)
    {
        await set_enabled_disabled_switch();
    }
    

    If you need to access the UI in a thread that is not the main thread, you need to use the DispatcherQueue.