【问题标题】:Set StaticResource style of a control in code behind在后面的代码中设置控件的 StaticResource 样式
【发布时间】:2014-10-24 10:42:27
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    这个问题被问到现在已经 4 年多了,但我想发布一个答案只是为了分享我的发现。

    比如App.xaml(Xamarin跨平台应用开发)的Application resource中描述有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"]
    };
    

    【讨论】:

      【解决方案2】:

      你可以用这个:

      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。
      【解决方案3】:

      你可以设置,像这样,

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

      【讨论】:

      • 我看到这是旧的,但有人知道如何用 FrameworkElementFactory(typeof(TextBlock)) 做同样的事情吗?
      猜你喜欢
      • 2010-11-27
      • 1970-01-01
      • 2012-01-21
      • 2013-05-05
      • 1970-01-01
      • 2017-12-27
      • 2012-09-30
      • 2011-07-08
      • 1970-01-01
      相关资源
      最近更新 更多