【问题标题】:How can I override a Foreground property with a Style after initialization?初始化后如何使用 Style 覆盖 Foreground 属性?
【发布时间】:2014-03-25 14:23:06
【问题描述】:

所以我在我的 Windows 8 应用程序中有一个 TextBlock 元素,我覆盖了这样的前景色:

TestTextBlock.Foreground = new SolidColorBrush(Color.FromArgb(255,255,0,0));

我想稍后使用具有不同前景色的样式覆盖此颜色。风格:

<Style TargetType="TextBlock" x:Key="MyStyle">
    <Setter Property="Foreground" Value="Yellow"/>
</Style>

覆盖:

TestTextBlock.Style = (Style) App.Current.Resources["MyStyle"];

现在如果我不先初始化 Foreground-property,这可以工作。似乎前景优先于样式。问题是这是一个简化的示例,我无法删除设置前景属性的代码行。

还有其他解决方法吗?我尝试设置 Foreground = null,但这导致文本不可见。

【问题讨论】:

    标签: xaml windows-8 microsoft-metro


    【解决方案1】:

    您可以根据需要设置默认颜色,然后我个人通过 Storyboard 运行ColorAnimation 之类的;

    <Storyboard x:Key="ChangeThatForegroundColor">
       <ColorAnimation Duration="0"
                       Storyboard.TargetName="YourTextBlockName"
                       Storyboard.TargetProperty="(Control.Foreground).(SolidColorBrush.Color)"
                       To="Yellow" />
    </Storyboard>
    

    您可以使用BeginStoryboard method 将其关闭。希望这会有所帮助。

    【讨论】:

    • 这绝对是一个解决方案,但感觉就像在工作中使用了错误的工具。如果在接下来的几天内没有其他答案,我会接受。
    • 呃,通常是在运行时完成的。因此,为什么您的默认控件模板也会这样做。
    【解决方案2】:

    希望这个帮助:它对我有用

     <TextBlock x:Name="TestTextBlock" Text="Hello world"/> 
    

    1)仅使用solidcolorbrush 覆盖SolidColorBrush

      void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            TestTextBlock.Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0));
            TestTextBlock.Foreground = new SolidColorBrush(Colors.Yellow);                       
        }
    

    2)仅用样式覆盖样式

     <Style x:Key="MyStyle" TargetType="TextBlock" >
        <Setter Property="Foreground" Value="Red"/>
    </Style>
    
    <Style x:Key="MyStyle1" TargetType="TextBlock" >      
        <Setter Property="Foreground" Value="Yellow"/>
    </Style>
    
      void MainPage_Loaded(object sender, RoutedEventArgs e)
        {          
            TestTextBlock.Style = (Style)App.Current.Resources["MyStyle"];
            TestTextBlock.Style = (Style)App.Current.Resources["MyStyle1"];            
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-05
      相关资源
      最近更新 更多