初始化Xamarin表单时不应用文本样式

问题描述 投票:0回答:1

我有一个UWP应用程序并试用嵌入式Xamarin表单。嵌入本身到目前为止工作。但是我注意到在初始化Forms之后某些TextStyles不再起作用了。

没有表格:enter image description here

在Forms.Init之后:enter image description here

唯一的区别是App.xaml.cs中的这一行:

Xamarin.Forms.Forms.Init(e);

TextBlock的代码是:

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

风格:

<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>

我在这里创建了一个最小的例子:https://github.com/NPadrutt/EmbeddedFormsTest

版本:

  • VS 15.5.2
  • Xamarin.Forms 2.5.0.121934
  • Microsoft.NETCore.UniversalWindowsPlatform 6.0.5
xamarin xamarin.forms uwp xamarin.uwp
1个回答
1
投票

当你执行Xamarin.Forms.Forms.Init(e);时,它将加载在Xamarin中定义的ResourceDictionary。因此,在调用此代码行之后,文本可能会显示Xamarin Forms中定义的样式,而不是您在UWP中定义的样式。您可以查看Init方法代码片段的详细信息。

更新:

Init方法通过此代码行合并样式

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

你会在Xamarin的Resource.xaml找到以下风格。

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

它与您定义的x:key(PageTitleStyle)相同,因此您的样式将被覆盖。只需更改您的风格的x:key,它就不会受到Xamarin资源的影响,例如PageTitleStyle2

如果您想使用您在UWP app中为Xamarin Forms定义的样式,可以使用Custom RenderersTextBlock是UWP的原生对照,Xamarin Forms中的对应控件是Label。详情请见Renderer Base Classes and Native Controls。你应该在Xamarin Forms中有一个Label控件并为Label创建一个自定义渲染器,并在UWP中设置目标类型为TextBlock的样式。例如:

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

如需更多样品,请参考this

© www.soinside.com 2019 - 2024. All rights reserved.