简体   繁体   中英

How to programmatically raise SizeChanged event

I'm trying to execute code in a SizeChangedEventHandler but the following is not working:

[TestMethod]
public void TestSizeChanged()
{
    var panel = new System.Windows.Controls.StackPanel();

    bool handled = false;
    panel.SizeChanged += (o, e) =>
    {
        handled = true; // how to get this to be executed
    };

    panel.Width = 100; // naive attempt to change size!

    Assert.IsTrue(handled);
}

I originally tried to use the RaiseEvent method but I was not been able to supply it with the correct xxxEventArgs type, due to not knowing the constructor arguments and the object browser is not helping:

panel.RaiseEvent(new System.Windows.SizeChangedEventArgs()) // does not compile

Obviously, the above test serves no purpose but I'm after correct way of getting the event to fire in a unit-tested environment.

It's very strange that the SizeChanged event doesn't fire with your code, it appears to be correct. Maybe the StackPanel doesn't exists in the visual tree because it's not really shown on the screen, so the event is never fired. Try to show a real window with a StackPanel on the screen, and programmatically change his width or height.

    [TestMethod]
    public void TestSizeChanged()
    {
        Window wnd = new Window();
        wnd.Content = new System.Windows.Controls.StackPanel();

        bool handled = false;
        wnd.SizeChanged += (o, e) =>
        {
            handled = true; // how to get this to be executed
        };

        wnd.Show();
        wnd.Width = 100; // naive attempt to change size!

        Assert.IsTrue(handled);

    }

You can't use the RaiseEvent method, because SizeChanged is not a RoutedEvent.

Using the below reflection you can succeed:

//panel =>System.Windows.Controls.Panel instance..
SizeChangedInfo sifo = new SizeChangedInfo(panel, new Size(0, 0), true, true);
SizeChangedEventArgs ea = typeof(System.Windows.SizeChangedEventArgs).GetConstructors(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).FirstOrDefault().Invoke(new object[] {(panel as FrameworkElement),sifo }) as SizeChangedEventArgs;
ea.RoutedEvent = Panel.SizeChangedEvent;
panel.RaiseEvent(ea);

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