我想你可能缺少了一些资源。如果你做了类似以下的操作:
<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>
那么您将会得到这样一个异常。我们甚至可以使用 ComponentResourceKey 来产生这个异常:
<Style TargetType="Button">
<Setter Property="Foreground" Value="{StaticResource {ComponentResourceKey TypeInTargetAssembly={x:Type FrameworkElement}, ResourceId=NoSuchResourceKey}}" />
</Style>
有几个问题会导致这个问题。通常,在使用StaticResource
时,你会得到编译器错误,指出资源不存在。比如在这种情况下:
<Button Content="Click Me" Foreground="{StaticResource NoSuchResourceKey}" />
如果我们改为这样做:
如果我们改为这样做:
<Button Content="Click Me" Foreground="{StaticResource {ComponentResourceKey TypeInTargetAssembly={x:Type FrameworkElement}, ResourceId=NoSuchResourceKey}}" />
然后你会得到一个不同的异常(XamlParseException),内容如下:
“在'System.Windows.StaticResourceExtension'上提供值引发了异常。行号为“6”,行位置为“22”。”
内部异常是:
“找不到名为'TargetType=System.Windows.FrameworkElement ID=NoSuchResourceKey'的资源。资源名称区分大小写。”
这一切都导致了真正的问题(缺少资源)。前两个示例不能给我们有用的异常的原因是,我们没有设置Foreground属性。我们正在设置Setter对象的Value属性。因此,当找不到资源时,将使用DependencyProperty.UnsetValue。这对于Setter.Value属性来说是完全有效的。
稍后,当样式应用于按钮时,我们会收到异常,因为这时DependencyProperty.UnsetValue实际上被分配给Button.Foreground属性。
要解决此问题,我建议在整个解决方案中搜索“Property =”Foreground“”,并查找任何使用不存在资源的实例。
我应该补充说明,当使用DynamicResource时,您不会收到异常,因为传递给Button.Foreground属性的值是“特殊值”(允许延迟查找)。除非找到资源,否则这个“特殊值”不会分配给给定的属性。