Skip to content

[Proposal] Add Overloaded Constructor to Style<T> that Accepts Microsoft.Maui.Controls.Style #274

@TheCodeTraveler

Description

@TheCodeTraveler

Feature name

Add Overloaded Constructor to Style<T> that Accepts Microsoft.Maui.Controls.Style

Link to discussion

dotnet/maui#19725 (comment)

Progress tracker

  • Android Implementation
  • iOS Implementation
  • MacCatalyst Implementation
  • Windows Implementation
  • Tizen Implementation
  • Unit Tests
  • Samples
  • Documentation

Summary

This Proposal adds another constructor to Style<T> that accepts. Microsoft.Maui.Controls.Style.

Motivation

The community has noted that it would be beneficial to easily convert Microsoft.Maui.Controls.Style to CommunityToolkit.Maui.Markup.Style<T>.

Detailed Design

// Additional Implicit Operator 
public static implicit operator CommunityToolkit.Maui.Markup.Style<T>(Microsoft.Maui.Controls.Style style) => new Style<T>(style);

// Additional Overloaded Constructor
public Style(Style mauiStyle)
{
  if (!mauiStyle.TargetType.IsAssignableTo(typeof(T)))
  {
	throw new ArgumentException($"Invalid type. The Type used in {nameof(mauiStyle)}.{nameof(mauiStyle.TargetType)} ({mauiStyle.TargetType.FullName}) must be assignable to the Type used in {nameof(Style<T>)} ({typeof(T).FullName})", nameof(mauiStyle));  
  }

  MauiStyle = mauiStyle;
}

Usage Syntax

Style mauiButtonStyle = new Style(typeof(Button));
Style<Button> markupButtonStyle_Constructor = new Style<Button>(mauiButtonStyle);
Style<Button> markupButtonStyle_Implicit = temp;

Drawbacks

I cannot think of any drawbacks at this time.

Alternatives

The current alternative to converting a Microsoft.Maui.Controls.Style to Style<T> is complicated and requires a for loop to move all of the BindableProperties from Style to Style<T>.

Unresolved Questions

Is there a valid use case where the type for MauiStyle.TargetType wouldn't match the type used for Style?

If not, I think it's best to throw an exception when !mauiStyle.TargetType.IsAssignableTo(typeof(T)).

E.g. The following code throws an InvalidArgumentException:

Style mauiLabelStyle = new Style(typeof(Label));

// Throws InvalidArgumentException
Style<Button> = mauiLabelStyle;

// Throws InvalidArgumentException
var buttonStyle = new Style<Button>(mauiLabelStyle);

Metadata

Metadata

Assignees

No one assigned

    Labels

    approvedchampionA member of the .NET MAUI Toolkit core team has chosen to champion this featurepending documentationThis feature requires documentationproposalA fully fleshed out proposal describing a new feature in syntactic and semantic detail

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions