Set StaticResource style of a control in code behind(在代码隐藏中设置控件的StaticResource样式)
本文介绍了在代码隐藏中设置控件的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样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:在代码隐藏中设置控件的StaticResource样式
基础教程推荐
猜你喜欢
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
