比方说,我有这样的东西(在 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 Cross-Platform App development) 中的应用程序资源中描述了一个 Style
BlueButton
,它可以如下使用
<?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"]
};
关于c# - 在代码中动态设置控件的 StaticResource 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25584890/