microsoft / wil

Windows Implementation Library
MIT License
2.58k stars 236 forks source link

[Proposal][WinUI] Easily create dependency properties #472

Open citelao opened 2 months ago

citelao commented 2 months ago

Today, creating a custom dependency property requires a lot of boilerplate. This change gets rid of most of it. With this change, you can add a new dependency property quickly:

// idl
runtimeclass BgLabelControl : Windows.UI.Xaml.Controls.Control
{
    // ...
    static Windows.UI.Xaml.DependencyProperty LabelProperty{ get; };
    String Label;
}
// .h
namespace winrt::BgLabelControlApp::implementation
{
    struct BgLabelControl : BgLabelControlT<BgLabelControl>
    {
        // ...

        // At some point in your app initialization, you want to call `BgLabelControl::EnsureLabelProperty`
        WIL_DEFINE_DP(BgLabelControl, Label, winrt::hstring);
    };
}

Versus before you'd have to (see example on MSDN):

  1. (Unchanged) IDL: Declare the IDL
  2. .h: Declare a static DP class variable
  3. .h: Declare a static DP getter function
  4. .cpp: Define memory for the static DP
  5. (If you want to be correct) .cpp: In your app, initialize the static DP during startup
  6. .h: Declare & define member getter & setter functions

What changed?

How tested?

sylveon commented 2 months ago

Suggestion: detect the IDL compiler in the header using #ifdef __midl and provide the same macros but for IDL. Or make a separate header for that.