unoplatform / uno

Build Mobile, Desktop and WebAssembly apps with C# and XAML. Today. Open source and professionally supported.
https://platform.uno
Apache License 2.0
8.76k stars 706 forks source link

Events are attached after dependency properties from XAML #4718

Open MartinZikmund opened 3 years ago

MartinZikmund commented 3 years ago

Current behavior

Properties set in XAML are set before the event handlers are attached. This causes problems for example with ToggleButton-based controls where the Checked event is not triggered when IsChecked is set in XAML.

Expected behavior

Event handlers should be attached before dependency properties are set.

How to reproduce it (as minimally and precisely as possible)

Consider the following custom control:

public partial class ToggleCustomControl : Control
{
    public ToggleCustomControl()
    {    
    }

    public bool MyProperty
    {
        get { return (bool)GetValue(MyPropertyProperty); }
        set { SetValue(MyPropertyProperty, value); }
    }

    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.Register("MyProperty", typeof(bool), typeof(ToggleCustomControl), new PropertyMetadata(false, OnChanged));

    private static void OnChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        System.Diagnostics.Debug.WriteLine("MyProperty changed");
    }

    private RoutedEventHandler _test;

    public event RoutedEventHandler Test
    {
        add
        {
        System.Diagnostics.Debug.WriteLine("Handler added");
            _test += value;
        }
        remove
        {
            _test -= value;

        }
    }    
}

Put it on a XAML page as follows:

<shared:ToggleCustomControl
    MyProperty="True"
    Test="X_Checked" />

Put breakpoints in the Test event "add" handler and in the OnChanged method. Notice that in case of UWP, the add is hit first and OnChanged afterwards, whereas in Uno OnChanged is hit first and add after.

Workaround

Environment

Nuget Package:

Nuget Package Version(s):

Affected platform(s):

Youssef1313 commented 3 years ago

https://user-images.githubusercontent.com/31348972/128346777-1a2910ea-0a3a-4a3f-8a24-304fc81b3083.mp4

I can't reproduce. @MartinZikmund Are you still able to reproduce?

jeromelaban commented 3 years ago

@Youssef1313 thanks for trying to repro. Can you attach the repro you created for future reference ?

Youssef1313 commented 3 years ago

Repro4718.zip

Youssef1313 commented 3 years ago

Sorry, I think it's reproducible. My bad!