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

21

假设我有这样的东西(在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个回答

26

这个问题被提出已经超过4年了,但我想发布一个答案来分享我的发现。

例如,如果在应用程序资源中描述了App.xaml(Xamarin跨平台应用程序开发)中的 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"]
};

13

你可以设置,像这样:

  TextBlock myTextBlock= new TextBlock ()
    {
        FontFamily = new FontFamily("Segoe UI Light");
        Style = Resources["TextBlockStyle"] as Style,
    };

我知道这是老的,但有没有人知道如何使用FrameworkElementFactory(typeof(TextBlock))来完成完全相同的事情? - grinder22

3
你可以使用这个:
Style textBlockStyle;
try
{
    textBlockStyle = FindResource("TextBlockStyle") as Style;
}
catch(Exception ex)
{
    // exception handling
}

if(textBlockStyle != null)
{
    myTextBlock.Style = textBlockStyle;
}

或者使用 TryFindResource 方法:

myTextBlock.Style = (Style)TryFindResource("TextBlockStyle");

我只认为这些调用是特定于Android的API。 - ToolmakerSteve

0
 private void initializedynamicButton()
    {
        pnlContent.Children.Clear();
        for (int i = 0; i < 25; i++)
        {
            Button btn = new Button();
           btn.Style = (Style)this.FindResource("GelButton");
            btn.Content = new
            {
                Text = "ButtonName_"+i.ToString(),
                ImagePath = "",
                Margin = new Thickness(0, 0, 0, 10)

            };
            btn.Tag = new { GroupID = i };
            btn.Click += new RoutedEventHandler(btn_Click);
            pnlContent.Children.Add(btn);
        }


    }

1
你的回答可以通过提供更多支持性信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人能够确认你的回答是否正确。你可以在帮助中心找到关于如何撰写好回答的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接