Xamarin.Forms 为特定平台设置特定样式

4
我将尝试使用一些特定样式来为我的UWP应用程序进行样式设计,而在其他平台上应该保持默认样式。
这是我的项目布局:

enter image description here

我尝试了以下事情: 在 Clients.Shared 中创建如下样式:

<Style x:Key="SomeStyle" TargetType="Button" />

Clients.Themes.UWP中添加相同的样式键以覆盖它,但没有成功。然后我尝试创建一个虚拟样式并使用onPlatform,但这也没有起作用,但我仍然认为这是正确的方法。我有以下代码:
<Style x:Key="DummyStyle" TargetType="Button">
    <Setter Property="Style">
        <Setter.Value>
            <OnPlatform x:Key="ButtonStyle" x:TypeArguments="Style">
                <On Platform="UWP" Value="{StaticResource SomeStyle}"></On>
            </OnPlatform>
        </Setter.Value>
    </Setter>
</Style>

我尝试过使用合并的ResourceDictionary.MergedDictionaries,但是我无法包含xaml。

有人有任何线索吗?

3个回答

1

试试这个:

<OnPlatform x:TypeArguments="Color" Android="Green" iOS="White" WinPhone="White"
        x:Key="PrimaryColor" />


<Style x:Key="ButtonColor" TargetType="Button">
    <Setter Property="BackgroundColor" Value="{StaticResource PrimaryColor}" />
</Style>

<Button Text="Hello" HorizontalOptions="StartAndExpand"
   Grid.Row="2" Grid.ColumnSpan="2" Style="{StaticResource ButtonColor}" />

在这个例子中,我定义了一个名为ButtonColor的按钮样式。除了Android平台,这个按钮将在所有平台上使用白色的BackgroundColor,而在Android平台上将使用绿色。我发现这是使用此标记进行样式设置时最常见的用法;如果您正在处理字体,请务必在模拟器和实际设备上运行以获得所需的字体。

3
只是颜色的话不够,我想要完整的风格。 - Kiwi
Visual Studio正在将OnPlatform中的Android等属性标记为过时。有什么替代方案吗? - Savage
@Savage - 在xaml中,有一种更新的“嵌套”语法,可以干净地处理其他平台。寻找关于<OnPlatform><<On Platform="Android" Value=.../></OnPlatform>的讨论。在C#中,使用switch (Device.RuntimePlatform)代替。 - ToolmakerSteve

1
这个语法对我有效:
<Style x:Key="zoneLabelStyle" TargetType="Label">
  <Setter Property="HeightRequest" Value="18" />
  <Setter Property="Margin">
    <OnPlatform x:TypeArguments="Thickness">
      <On Platform="Android" Value="0, -3, 0, 0" />
    </OnPlatform>
  </Setter>
</Style>

0

为什么不使用

<Button.Style>
    <OnPlatform x:TypeArguments="x:Style">
        <OnPlatform.iOS>...</OnPlatform.iOS>
        <OnPlatform.Android>...</OnPlatform.Android>
        <OnPlatform.WinPhone>...</OnPlatform.WinPhone>
    </OnPlatform>
</Button.Style>

希望它能够有所帮助。


1
问题在于我无法加载样式 :) - Kiwi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接