Anyway to bypass control event firing during Page.Loaded event?

杨岑 166 Reputation points
2024-05-07T15:29:15.5566667+00:00

Simplified scenario:

<ToggleButton x:Name="fuzzySearchToggle"
              Checked="fuzzySearchToggle_Checked"
              Unchecked="fuzzySearchToggle_Checked"/>
        bool _loading = true;

        private async void Pge_Loaded(object sender, RoutedEventArgs e)
        {
            // PROBLEM:
            //
            // Setting IsChecked triggers fuzzySearchToggle_Checked
            // which saves the value back to UserSettings which is quite redundant.
            fuzzySearchToggle.IsChecked = UserSettings.FuzzySearch;
            _loading = false;
        }

        private void fuzzySearchToggle_Checked(object sender, RoutedEventArgs e)
        {
            if (_loading) return;
            UserSettings.FuzzySearch = fuzzySearchToggle.IsChecked == true;
        }

The _loading variable works for ToggleButton but not for TextBox because during debugging I see that minSizeTextBox_TextChanged is fired after Page.Loaded completes.

This is a real delima. Is there any elegant way to solve this chicken-egg problem?

Universal Windows Platform (UWP)
{count} vote

1 answer

Sort by: Most helpful
  1. 杨岑 166 Reputation points
    2024-05-10T09:09:42.37+00:00

    I found a solution myself.

    I removed event hoopups in XAML markup and hook up all the events in Page.Loaded event, after all initialization is done.

    void Page_Loaded(object sender, RoutedEventArgs e)
    {
        // do intialization
        textbox1.Text = Settings.value1;
        // other controls
    
        // then hook up events
        textbox1.TextChanged += textbox1_TextChanged;
        // other controls
    }
    

    But this effectively defeats the purpose of XAML markup because in WPF/UWP we are persuaded/forced to use markup as much as possible.

    0 comments No comments