microsoft / microsoft-ui-xaml

WinUI: a modern UI framework with a rich set of controls and styles to build dynamic and high-performing Windows applications.
MIT License
6.38k stars 683 forks source link

`FindName()` does not work when root object is a Window #9842

Open HO-COOH opened 4 months ago

HO-COOH commented 4 months ago

Describe the bug

FindName() does not work in WinUI3, while the exact same code works in UWP.

Steps to reproduce the bug

  1. Create a new C++WinUI3 packaged project
  2. Use this xaml
    <StackPanel x:Name="Root" Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center" Spacing="5">
        <Button x:Name="myButton" Click="myButton_Click">Click to load</Button>
        <Rectangle x:Name="DelayLoadRect" Fill="Green" Width="100" Height="50" x:Load="False" Loaded="Rectangle_Loaded"/>
    </StackPanel>
  3. Use this code

    void MainWindow::myButton_Click(IInspectable const&, RoutedEventArgs const&)
    {
        static bool IsLoaded = false;
        if (IsLoaded)
        {
            winrt::Microsoft::UI::Xaml::Markup::XamlMarkupHelper::UnloadObject(DelayLoadRect());
            myButton().Content(box_value(L"Click to load"));
        }
        else
        {
            myButton().Content(box_value(L"Click to unload"));
            auto delayLoadRect = Root().FindName(L"DelayLoadRect");
        }
        IsLoaded = !IsLoaded;
    }
    
    void MainWindow::Rectangle_Loaded(winrt::Windows::Foundation::IInspectable const& sender, winrt::Microsoft::UI::Xaml::RoutedEventArgs const& e)
    {
        winrt::Microsoft::UI::Xaml::Controls::ContentDialog dialog;
        dialog.XamlRoot(Content().XamlRoot());
        dialog.Title(winrt::box_value(L"Loaded"));
        dialog.PrimaryButtonText(L"OK");
        dialog.ShowAsync();
    }
  4. Build and run, the green rect is not loaded. The dialog is not shown.

Repro here

Expected behavior

No response

Screenshots

No response

NuGet package version

WinUI 3 - Windows App SDK 1.5.5: 1.5.240627000

Windows version

Windows 11 (22H2): Build 22621

Additional context

No response

eduardobragaxz commented 4 months ago

Try it on a page instead.

HO-COOH commented 4 months ago

Try it on a page instead.

Moving it to a Page does work, but I think the fact that it does not work under Window needs to be documented.