在后面的代码中设置控件的StaticResource样式

kodi1911

假设,我有这样的东西(在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));
3not3

自问这个问题以来已经有4年多了,但是我想发表一个答案只是为了分享我的发现。

例如,如果Style BlueButtonApp.xaml(Xamarin跨平台应用程序开发)的“应用程序”资源中描述,则可以按以下方式使用它

<?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"]
};

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在后面的代码中访问DataTemplate控件

在后面的代码中设置AutomationProperties.AutomationId

在后面的代码中设置x:DeferLoadStrategy

在后面的代码中设置 RenderFragment 默认内容

绑定控件在后面的代码中被检查

如何在后面的代码中访问控件库?

Xamarin.Forms-在后面的代码中更改控件的大小

上传文件控件未在后面的代码中显示任何文件

WPF如何在后面的代码中设置Gridview绑定中的复选框

如何在后面的代码中设置视频标签的来源?

如何在后面的代码中设置框架的高度请求?

在后面的代码中设置Xamarin.Forms绑定CommandParameter

在后面的代码中设置图片的网址时无法渲染图片

如何在后面的代码中设置WPF ApplicationCommands

如何在后面的代码中设置type =“ password”的文本框的文本

可以在后面的代码中设置DataGrid.Resources吗?

WPF 在后面的代码中设置 DataTemplate 网格大小(ResourceDictionary)

在后面的代码中使用 StaticResource 和 x:Static

在后面的代码中更改Label的ContentStringFormat属性

回复:资源无法在后面的代码中访问

在后面的代码中从ResourceDictionary检索值

在后面的代码中创建treeview json

在后面的代码中创建jqGrid列模型

在后面的代码中获取li标签的值

在后面的代码中调用按钮的OnClientClick

在后面的代码中更改徽章颜色

将表单保存在后面的代码中

在后面的代码中获取原始 ViewState 数据

在后面的代码中创建contentcontrol