XAML 在代码中动态设置控件的StaticResource样式

xxe27gdn  于 2022-12-07  发布在  其他
关注(0)|答案(3)|浏览(161)

比如说,我有这样的代码(在MainPage.xaml中):

<Page.Resources>
    <Style TargetType="TextBlock" x:Key="TextBlockStyle">
        <Setter Property="FontFamily" Value="Segoe UI Light" />
        <Setter Property="Background" Value="Navy" />
    </Style>
</Page.Resources>

然后,我想将该StaticResource样式应用于动态创建的TextBlock(文件MainPage.xaml.cs)。
有没有可能这样做而不是这样做:

myTextBlock.FontFamily = new FontFamily("Segoe UI Light");
myTextBlock.Background = new SolidColorBrush(Color.FromArgb(255,0,0,128));
wixjitnu

wixjitnu1#

自从这个问题被问到现在已经4年多了,但我想发布一个答案,只是为了分享我的发现。
例如,如果App.xaml(Xamarin跨平台应用程序开发)中的应用程序资源中描述了一个StyleBlueButton,则可以如下使用

<?xml version="1.0" encoding="utf-8" ?><Application xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="SharedUi.App">
<Application.Resources>
    <ResourceDictionary>
        <Style x:Key="BlueButton" TargetType="Button">
            <Setter Property="TextColor" Value="White" />
            <Setter Property="FontSize" Value="20" />
            <Setter Property="BackgroundColor" Value="Blue"/>
            <Setter Property="HeightRequest" Value="70"/>
            <Setter Property="FontAttributes" Value="Bold"/>
        </Style>            
    </ResourceDictionary>
</Application.Resources></Application>

然后在代码后面

Button newButton1 = new Button
{
    Text = "Hello",
    WidthRequest = (double)15.0,
    Style = (Style)Application.Current.Resources["BlueButton"]
};
juud5qan

juud5qan2#

你可以设置,像这样的东西,

TextBlock myTextBlock= new TextBlock ()
    {
        FontFamily = new FontFamily("Segoe UI Light");
        Style = Resources["TextBlockStyle"] as Style,
    };
x8goxv8g

x8goxv8g3#

您可以使用此选项:

Style textBlockStyle;
try
{
    textBlockStyle = FindResource("TextBlockStyle") as Style;
}
catch(Exception ex)
{
    // exception handling
}

if(textBlockStyle != null)
{
    myTextBlock.Style = textBlockStyle;
}

TryFindResource方法:

myTextBlock.Style = (Style)TryFindResource("TextBlockStyle");

相关问题