简体   繁体   中英

Avoid SizeChanged event on startup

I have a MainWindow Class which as a few Events - all of them should call a method in another class.

  public partial class MainWindow : Window
    {

        public MainWindow()
    {          
        InitializeComponent();

        getdata.MainWindow = this; 
    }


    private void button_Click(object sender, RoutedEventArgs e)
    {
        getdata go = new getdata();
        go.clear();
    }

    private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        getdata go = new getdata();
        go.clear();
    }

private void comboBox2_DropDownClosed(object sender, EventArgs e) 
    {

        getdata go = new getdata();
        go.clear();

    }

    private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e)         {
        getdata go = new getdata();
        go.clear();  //<-this causes exception on Startup 
    }

}

The Problem is that the MainWindow_SizeChanged Event is also triggered on Startup of the program but the clear method uses also some objects that are not yet created at Startup, which causes an error. How can I avoid this and only have this Event triggered when the size is actually changed while running the program?

You have the IsLoaded property of Window.

You can check it before executing code.

You can check if an item is null when re-sizing so you can avoid this being an issue, this can be done using the null coalescence and null conditional operators. If for example you are using the value of a textBox on startup but it has not been instantiated you can use this

string someText = tB1?.Text?
if(someText == null) return;

SizeChanged Event gets triggered before the window is loaded. You can try subscribing to the SizeChanged event as part of Loaded event and unsubscribe it in the Unloaded as shown below.

//XAML
<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        Loaded="Window_Loaded" 
        Unloaded="MainWindow_OnUnloaded">

//Code Behind
private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
{
    Debug.WriteLine("Size Changed Triggered");
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    SizeChanged += Window_SizeChanged;
}

private void MainWindow_OnUnloaded(object sender, RoutedEventArgs e)
{
    SizeChanged -= Window_SizeChanged;
}

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