microsoft / cppwinrt

C++/WinRT
MIT License
1.61k stars 232 forks source link

Bug:Since 2.0.240111.5, I get a compile error with the GetTemplateChild function. #1393

Closed takatsuka2022 closed 4 months ago

takatsuka2022 commented 4 months ago

Version

2.0.240111.5

Summary

I think GetTemplateChild was a public function, but since 2.0.240111.5 it has been changed to protected, so I cannot access it from outside the class. Is there a workaround for this?

Reproducible example

.xaml
<ColorPicker x:Name="MemoColorPicker" Grid.Row="0" Grid.Column="1" Margin="20,10,30,0"
 ColorSpectrumShape="Box" IsAlphaSliderVisible="False" IsColorPreviewVisible="False"
 IsColorChannelTextInputVisible="False" IsHexInputVisible="False" IsColorSliderVisible="False"/>

.cpp
auto spectrum = MemoColorPicker().GetTemplateChild(L"ColorSpectrum").try_as<Controls::Primitives::ColorSpectrum>();
if (spectrum != nullptr) {
    auto tool_chip = spectrum.GetTemplateChild(L"ColorNameToolTip").try_as<Controls::ToolTip>();
    if (tool_chip != nullptr) tool_chip.Visibility(Visibility::Collapsed);
}

Expected behavior

No response

Actual behavior

No response

Additional comments

No response

dmachaj commented 4 months ago

This seems to be related to #1319. Adding a .as or .try_as cast from spectrum to xaml::FrameworkElement before calling GetTemplateChild should fix the break.

Also @sylveon for a second opinion on this topic.

sylveon commented 4 months ago

GetTemplateChild has always been a protected method in WinRT metadata so this is an intentional result of this change. It was never meant to be public.

You can quickly workaround this issue by doing .as<IControlProtected>().GetTemplateChild(), however the proper way to do what you're trying to do here is to extend ColorPicker and override OnApplyTemplate, or retemplate ColorPicker.

takatsuka2022 commented 4 months ago

auto spectrum = MemoColorPicker().as<IControlProtected>().GetTemplateChild(L"ColorSpectrum").try_as<Controls::Primitives::ColorSpectrum>();

I wrote the above code, but the return value is NULL. Is this wrong?

sylveon commented 4 months ago

This seems to work as expected for me: image

Does your code work as expected with the previous versions of cppwinrt? Perhaps it runs before the template gets applied.

takatsuka2022 commented 4 months ago

The problem has been resolved successfully. Thank you very much.