繁体   English   中英

从 C# 访问样式资源 - Xamarin.Forms

[英]Accessing Style Resources from C# - Xamarin.Forms

我正在使用 Xamarin.Forms 应用程序。 我在 App.xaml 中定义的以下样式

<Application.Resources>
    <ResourceDictionary>
        <Style x:Key="blueButton" TargetType="Button">
            <Setter Property="BackgroundColor"
                    Value="Blue" />
            <Setter Property="TextColor"
                    Value="White" />
        </Style>            
    </ResourceDictionary>
</Application.Resources>

当我想使用 MainPage.xaml 中的样式时,它工作得很好。

<Button x:Name="CreateGridButton" 
            Margin="0,15,0,0"
            Clicked="CreateGridButton_Clicked"
            Text="Create Grid Layout" Style="{StaticResource blueButton}" />

但是,当我想从 MainPage.xaml.cs 执行相同操作时,它会显示错误消息“当前上下文中不存在名称‘blueButton’”。

Button createSL = new Button();
        createSL.Text = "Create Stack Layout";
        createSL.Style = (Style)Resources["blueButton"];

我也尝试了以下,也显示了同样的错误。

createSL.Style = bluebutton;

根据我的要求,我无法在 XAML 中创建此按钮。 所以请帮助我从背后的代码中做到这一点。

由于您在 App.xaml 中定义了您的样式:

createSL.Style = (Style)Application.Current.Resources["blueButton"];

请尝试这样做

在您的 App 构造函数中创建样式并将其添加到资源中,如下所示:

public App ()
    {
        var buttonStyle = new Style (typeof(Button)) {
            Setters = {
                ...
                new Setter { Property = Button.TextColorProperty,   Value = Color.Teal }
            }
        };

        Resources = new ResourceDictionary ();
        Resources.Add ("blueButton", buttonStyle);
        ...
    }

之后使用此样式并设置为这样的按钮:

Button createSL = new Button();
createSL.Text = "Create Stack Layout";
createSL.Style = (Style)Application.Current.Resources ["blueButton"];

可以在本地和应用程序级别定义样式:

var buttonWithStyleFromLocalResources = button1; //button1 defined in XAML
var buttonWithStyleFromApplicationResources = button2; //button2 defined in XAML

ResourceDictionary localResourceDictionary = Resources;

//try to access local style with key "KeyForStyle"
if (localResourceDictionary.TryGetValue("KeyForStyle", out object value) && value is Style)
{
  buttonWithStyleFromLocalResources.Style = (Style)value;
}

//try to access application style with key "KeyForStyle" (from App.xaml)
ResourceDictionary applicationResourceDictionary = Application.Current.Resources;

if (applicationResourceDictionary.TryGetValue("KeyForStyle", out value) && value is Style)
{
  buttonWithStyleFromApplicationResources.Style = (Style)value;
}

上下文:Xamarin Forms,C#。

我开发了函数 GetStyleFromApplicationResource() 用于在我的项目中从代码加载标签样式。

下面是一个从本地或应用程序资源字典加载样式的类。 包含一个示例 XAML 和 XAML.cs 文件来回答原始发布者的问题。

感谢@Benl 指出了本地资源和应用程序资源之间的区别。

//GenFunc.cs
namespace MyApp
{
    public static class GenFunc
    {
        public static Style GetStyleFromLocalResource(ResourceDictionary localresource, String ResourceNameKey)
        {
            if( (localresource.TryGetValue(ResourceNameKey, out Object retValue)) &&
                (retValue is Style value))
            {
                return value;
            }
            throw new Exception($"Style '{ResourceNameKey}' not found in local ResourceDictionary");
        }

        public static Style GetStyleFromApplicationResource(String ResourceNameKey)
        {
            if( (Application.Current.Resources.TryGetValue(ResourceNameKey, out Object retValue)) &&
                (retValue is Style value))
            {
                return value;
            }
            throw new Exception($"Style '{ResourceNameKey}' not found in Application ResourceDictionary");
        }
    }
}

//Test.xaml.cs
using MyApp;
using System;
using System.Reflection;
using Xamarin.Forms;

namespace MyApp.Pages
{
    public partial class Test : ContentPage
    {
        public Test()
        {
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();

            Style btnStyle = new Style(typeof(Button));

            try
            {
                lblStyle = GenFunc.GetStyleFromLocalResource(Resources, "blueButton");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            try
            {
                lblStyle = GenFunc.GetStyleFromApplicationResource("blueButton");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            Button createSL = new Button();
            createSL.Text = "Create Stack Layout";
            createSL.Style = btnStyle;

            SL0.Children.Add(createSL);
        }
    }
}

//Test.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage Title="Test"
             xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core" 
             x:Class="MyApp.Pages.Test"
             ios:Page.UseSafeArea="true">
    <ContentPage.Content>
        <StackLayout x:Name="SL0" Margin="10,0">
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM