0
votes

I have a UWP app and try out Embedded Xamarin Forms. The embedding itself works so far. But I noticed that certain TextStyles do no longer work after I initialized Forms.

Without Forms: enter image description here

After Forms.Init: enter image description here

The only difference is this Line in the App.xaml.cs:

Xamarin.Forms.Forms.Init(e);

The Code of the TextBlock is:

<TextBlock x:Name="TitlePage"
                   Text="Hello"
                   Style="{StaticResource PageTitleStyle}" />

And the style:

<Style x:Key="PageTitleStyle"
       TargetType="TextBlock">
    <Setter Property="VerticalAlignment"
            Value="Center" />
    <Setter Property="FontWeight"
            Value="SemiLight" />
    <Setter Property="FontSize"
            Value="{StaticResource LargeFontSize}" />
    <Setter Property="TextTrimming"
            Value="CharacterEllipsis" />
    <Setter Property="TextWrapping"
            Value="NoWrap" />
    <Setter Property="Margin"
            Value="{StaticResource PageTitleMargin}" />
</Style>

I created a minimal example which you can find here: https://github.com/NPadrutt/EmbeddedFormsTest

Versions:

  • VS 15.5.2
  • Xamarin.Forms 2.5.0.121934
  • Microsoft.NETCore.UniversalWindowsPlatform 6.0.5
1

1 Answers

1
votes

When you execute Xamarin.Forms.Forms.Init(e);, it will load the ResourceDictionary which defined in Xamarin. So that after this code line invoked, the text may show the style defined in Xamarin Forms, not the style you defined in UWP. Details you can check the code snippet of Init method.

Updated:

The Init method merge the style by this code line

return new Windows.UI.Xaml.ResourceDictionary {
Source = new Uri("ms-appx:///Xamarin.Forms.Platform.UAP/Resources.xbf")

And you will find the following style in Resource.xaml in Xamarin.

<Style x:Key="PageTitleStyle" TargetType="TextBlock">
    <Setter Property="FontWeight" Value="Bold" />
</Style>

Which has same x:key (PageTitleStyle) as you defined so that your style will be override. Just change the x:key of your style it will not be influenced by the Xamarin resources,for example PageTitleStyle2.

If you want to use the style you defined in UWP app for the Xamarin Forms, you could use Custom Renderers. TextBlock is the native control for UWP, the correspondent control in Xamarin Forms is Label. Details please see Renderer Base Classes and Native Controls. You should have a Label control in Xamarin Forms and create a custom renderer for Label and set the style with target type is TextBlock in UWP. For example:

public class MyLabelRenderer : LabelRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
    {
        base.OnElementChanged(e);
        Control.Style= (Windows.UI.Xaml.Style)App.Current.Resources["PageTitleStyle"];
    }
}

For more samples you could reference this.