在代码隐藏中设置控件的StaticResource样式 [英] Set StaticResource style of a control in code behind

查看:45
本文介绍了在代码隐藏中设置控件的StaticResource样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有如下内容(在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));

推荐答案

这个问题已经提出4年多了,但我想发布一个答案,只是为了分享我的发现。

App.xaml(Xamarin跨平台App开发)中的应用资源中描述的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"]
};

这篇关于在代码隐藏中设置控件的StaticResource样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆