【问题标题】:Text Style not applied when Xamarin Forms is initialized初始化 Xamarin Forms 时未应用文本样式
【发布时间】:2018-05-30 04:35:56
【问题描述】:

我有一个 UWP 应用并试用 Embedded Xamarin Forms。嵌入本身到目前为止有效。但我注意到某些 TextStyles 在我初始化 Forms 后不再起作用。

没有表格:

Forms.Init 之后:

唯一不同的是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】:

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

    更新:

    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 应用中为 Xamarin 窗体定义的样式,你可以使用 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

    【讨论】:

    • 感谢您的回答。可以肯定的是,当我初始化 xamarin 表单时,我的原生 UWP 控件的所有样式都将停止工作?由于上面显示的 Textblock 位于 UWP 的本机 MainPage 中。
    • @NPadrutt,不适合所有人。正如我上面提到的,init 方法合并了 Xamarin 中的 Resource,它只包含与您定义的相同名称的样式。我会更新我的回复以使其更清楚。
    • @sunteen-wu-msft 啊,好的。这解释了它。我的原生 UWP 样式被 xamarin 样式覆盖。我只需要为我的原生 UWP 样式调整名称。感谢您的解释!! :)
    猜你喜欢
    • 2020-01-11
    • 1970-01-01
    • 2017-03-09
    • 2017-01-19
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 2015-03-03
    相关资源
    最近更新 更多