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