在资源字典中的样式中绑定 Setter 值



我正在尝试创建一个使用皮肤/主题的应用程序(使用可以选择不同的颜色托盘)。

我定义了一个SolidColorBrush属性

public class ThemeManager
{
    public SolidColorBrush ForeBrush { get; set; }       
    public ThemeManager()
    {
        ForeBrush = new SolidColorBrush(Colors.Black);         
    }
    public void SetTheme()
    {        
        ForeBrush.Color = Colors.Red;
    }
}

并将其绑定到 XAML 中

<TextBlock Foreground="{Binding ForeBrush,Source={StaticResource Theme}}" />

我在 App.xaml 中声明主题资源

<local:ThemeManager x:Key="Theme" />

问题是当我制作这样的样式时:

<Style x:Key="TextBlockStyle1" TargetType="TextBlock">
     <Setter Property="Foreground" Value="{Binding ForeBrush,Source={StaticResource Theme}}" />
</Style>

如果我将其放在 Page.Resources 中,这有效,但是如果我将其放在资源字典中(并将其添加到 App.xaml),应用程序会崩溃( App.g.i.cs 中的调试器.Break()。这似乎只在使用二传手时发生。

我在这里做错了什么?

编辑:将样式放在资源字典文件中并在 app.xaml 中引用该样式

使用此代码,它可以在我的 PC 上运行(使用 .NET 4.0)

这是字典

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:local="clr-namespace:Resources4">
<local:ThemeManager x:Key="Theme"></local:ThemeManager>
<Style TargetType="TextBlock">
    <Setter Property="Foreground" Value="{Binding ForeBrush,Source={StaticResource  Theme}}" />
</Style>
</ResourceDictionary>

下面是 XAML 中的参考

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Dictionary1.xaml"></ResourceDictionary>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

如果你写

<Application.Resources>
    <ResourceDictionary>
        <local:ThemeManager x:Key="Theme" />
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Dictionary1.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

然后,由于合并的资源字典的工作方式,您会收到错误。根据MSDN

合并

字典中的资源在资源查找作用域中占据一个位置,该位置紧随它们合并到的主资源词典作用域之后

这意味着在 Dictionary1.xaml 中,无法看到 App.XAML 中定义的资源

最新更新