c# - 在代码中动态设置控件的 StaticResource 样式

标签 c# xaml windows-phone-8 windows-phone-8.1

比方说,我有这样的东西(在 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/

相关文章:

c# - 在鼠标悬停时更改标签前景,但标签在按钮内容内

c# - 我可以在我的应用程序不运行的情况下定期在 WP8 中运行后台任务吗?

javascript - 网络浏览器未在 Windows Phone 8 上加载页面内容

c# - 使用左连接的 LINQ orderby FK

C# 任务异步等待智能卡 - UI 线程阻塞

c# - MVC 5 bundles.ignoreList.Clear 不起作用

c# - 如何找到距某个点 X 距离的经纬度?

C# 用户控件需要在最终应用程序中访问外部 cs 文件

wpf - 在 WPF 中加载外部图像

c# - Windows Phone 8.1 中 ContentDialog 的边框