I want you to have the missing resource. If you do something like:
<Window x:Name="window" x:Class="WpfApplication4.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:local="clr-namespace:WpfApplication4" Title="MainWindow" Height="350" Width="525" > <Window.Resources> <Style TargetType="Button"> <Setter Property="Foreground" Value="{StaticResource NoSuchResourceKey}" /> </Style> </Window.Resources> <StackPanel> <Button Content="Click Me" /> </StackPanel> </Window>
Then you will get such an exception. We can even use ComponentResourceKey to create this exception:
<Style TargetType="Button"> <Setter Property="Foreground" Value="{StaticResource {ComponentResourceKey TypeInTargetAssembly={x:Type FrameworkElement}, ResourceId=NoSuchResourceKey}}" /> </Style>
There are a few things that are causing the problem. Typically, you will get a compiler error indicating that the resource does not exist when using StaticResource
. For example, in this case:
<Button Content="Click Me" Foreground="{StaticResource NoSuchResourceKey}" />
If instead we did:
<Button Content="Click Me" Foreground="{StaticResource {ComponentResourceKey TypeInTargetAssembly={x:Type FrameworkElement}, ResourceId=NoSuchResourceKey}}" />
Then you will get another exception (XamlParseException) by saying:
Provide a value in "System.Windows.StaticResourceExtension". Line number "6" and line position "22".
With an internal exception:
Cannot find a resource with the name "TargetType = System.Windows.FrameworkElement ID = NoSuchResourceKey". Resource names are case sensitive.
All this leads us to a real problem (a missing resource). The reason the first two examples do not give us a useful exception is because we do not set the Foreground
property. We set the Value
property to the Setter
object. Therefore, when the resource is not found, DependencyProperty.UnsetValue
used. This is great for the Setter.Value
property.
Later, when Style
is applied to the Button
, we get an exception, because the one when DependencyProperty.UnsetValue
actually assigned to the Button.Foreground
property.
To fix this problem, I would search your entire solution for Property="Foreground"
and look for any instances that use a resource that does not exist.
I must add that you are not getting an exception when using DynamicResource
, because this value passed to the Button.Foreground
property has a "special value" (which allows you to delay the search). This "special value" will not assign the specified property if the resource is not found.