Reputation: 4373
I'm trying to create an app that uses skins/themes (different color pallets the use can choose from).
I define a SolidColorBrush
property
public class ThemeManager
{
public SolidColorBrush ForeBrush { get; set; }
public ThemeManager()
{
ForeBrush = new SolidColorBrush(Colors.Black);
}
public void SetTheme()
{
ForeBrush.Color = Colors.Red;
}
}
and bind it in XAML
<TextBlock Foreground="{Binding ForeBrush,Source={StaticResource Theme}}" />
I declare the Theme resource in App.xaml
<local:ThemeManager x:Key="Theme" />
The problem is when I make a style like:
<Style x:Key="TextBlockStyle1" TargetType="TextBlock">
<Setter Property="Foreground" Value="{Binding ForeBrush,Source={StaticResource Theme}}" />
</Style>
This works if I place it in Page.Resources
, but if I place it in a Resource Dictionary (and add it to App.xaml) the app crashes ( Debugger.Break() in App.g.i.cs).
This only seems to happen when using a Setter.
What am I doing wrong here?
EDIT: placing the style in a Resource Dictionary file and referencing that in app.xaml
Upvotes: 2
Views: 8243
Reputation: 11896
With this code it works on my PC (with .NET 4.0)
Here is the Dictionary
<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>
Here is the reference in XAML
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Dictionary1.xaml"></ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
If you write
<Application.Resources>
<ResourceDictionary>
<local:ThemeManager x:Key="Theme" />
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Dictionary1.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
Then you get an error because of how merged resource dictionary works. According to MSDN
Resources in a merged dictionary occupy a location in the resource lookup scope that is just after the scope of the main resource dictionary they are merged into
This means that in Dictionary1.xaml it is not possible to see a resource defined in App.XAML
Upvotes: 3