0

我对名为HeadText. TargetType = "TextBlock"样式定义Foreground和。第一次显示 TextBlock 时,仅未触发 Foreground setter(文本颜色保持黑色),FontSize 和 Effect 正常应用。当我从父级中删除 TextBlock 并将其返回时,前景也会发生应有的变化。FontSizeEffect

情况:

Presenter.dll 程序集

  • class Presenter: Window,加载并显示我的用户控件。
  • Generic.xaml- 包含样式的资源字典。
  • Presenter.dll不直接引用TestPresentable.dll

TestPresentable.dll 程序集

  • TestPresentable: UserControl, 有风格TextBlock
  • TestPresentable.dll不直接引用Presenter.dll

主应用程序

  • 引用以前的两个程序集,
  • MainWindow从程序集实例化Presenter.dll
  • TestPresentable从程序集实例化TestPresentable
  • MainWindow.ContentHost.Content = testPresentable

相关代码:

演示者.dll

// Themes/Generic.xaml
...
<Style TargetType="{x:Type TextBlock}" x:Key="HeadText">
    <Setter Property="Foreground" Value="#FFFFFFFF" />
    <Setter Property="Effect">
        <Setter.Value>
            <DropShadowEffect ShadowDepth="0" Color="#79000000" BlurRadius="3" Opacity="1" />
        </Setter.Value>
    </Setter>
    <Setter Property="FontSize" Value="24"/>
</Style>
...


// MainWindow.xaml
...
<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Presenter.dll;component/Themes/Generic.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Window.Resources>
<Grid>
    <ContentPresenter Name="ContentHost"/>
</Grid>
...

TestPresentable.dll

// TestPresentable.xaml
...
<TextBlock Text="{Binding SomeData}" Style="{DynamicResource HeadText}"/>
...
4

2 回答 2

7

自 3.5 以来,WPF 中的 TextBlock.Foreground 似乎有些奇怪,请参阅:

我想出了一个使用 EventSetters 和一些用于 ResourceDictionary 的代码隐藏的解决方法。这并不漂亮,但如果我想让我的样式独立于主应用程序,就必须这样做。我会在这里发布它,因为它可能对某人有用,如果有人发布正确(或更好)的答案,我将保持问题开放。

解决方法

在 ResorceDictionary XAML(例如 Generic.xaml)中添加一个 Class 属性,如下所示:

<!-- Generic.xaml -->
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="Presenter.Themes.Generic">

然后使用您在 ResourceDictionary 的 Class 属性中指定的部分类添加代码隐藏 cs 文件(例如 Generic.xaml.cs):

// Generic.xaml.cs
partial class Generic { }

在 ResourceDictionary 的相关样式中,为 Loaded 事件添加一个 EventSetter:

<!-- Generic.xaml -->
<Style TargetType="{x:Type TextBlock}" x:Key="HeadText">
    <EventSetter Event="Loaded" Handler="OnHeadTextLoaded"/>
    <Setter .../>
    <Setter .../>
    <Setter .../>
</Style>

在 Generic.xaml.cs 中为 Loaded 事件添加一个处理程序并设置所需的前景

//Generic.xaml.cs
public void OnHeadTextLoaded(object sender, EventArgs args)
{
    var textBlock = sender as TextBlock;
    if (textBlock == null) return;
    textBlock.Foreground = new SolidColorBrush(Colors.White);
}
于 2011-07-04T09:43:50.437 回答
1

第一次加载页面时,前景色没有通过类似的问题。我发现在我的情况下,如果您FontFamily在 xaml 文件中对属性进行硬编码TextBlock,那么前景色第一次会正确显示。

但是,如果您只是将FontFamily属性放在样式表中,那么第TextBlock一次将再次变为黑色。

例如

// TestPresentable.xaml

...
Style="{DynamicResource HeadText}" **FontFamily="Arial"**... 
于 2012-05-17T08:57:27.150 回答