XAML 如何为c#内容页中的项设置样式?

2nc8po8w  于 2022-12-07  发布在  C#
关注(0)|答案(1)|浏览(183)

我在Styles.xaml中添加了以下样式。

<Style x:Key="ButtonOutline" TargetType="Button">
        <Setter Property="BackgroundColor" Value="{AppThemeBinding Dark={StaticResource ButtonColorDark}, Light={StaticResource ButtonColor}}" />
        <Setter Property="TextColor" Value="{AppThemeBinding Dark={StaticResource TextColorDark}, Light={StaticResource TextColor}}" />
        <Setter Property="BorderColor" Value="{StaticResource Primary}" />
        <Setter Property="BorderWidth" Value="2" />
        <Setter Property="Margin" Value="10" />
        <Setter Property="HeightRequest" Value="50" />
</Style>

我想用C#设置样式。如果我这样做

grid.Add(new Button
        {
            Text = "Clear",
            Style = Style.LoadFromXaml("ButtonOutline")
            
        }, 1, 1);

然后程序崩溃,并出现System.Xml.XmlException: 'Data at the root level is invalid. Line 1, position 1.'异常。

fwzugrvs

fwzugrvs1#

Loadfromxaml不起作用,不知道为什么。我可以使用以下命令获得样式:

Application.Current.Resources.TryGetValue("ButtonOutline", out object buttonStyle);
grid.Add(new Button
    {
    Text = "Clear",
    Command = vm.ClearCommand,
    Style = (Style)buttonStyle
}, 1, 1);

相关问题