Visual Studio无可用来源

Kye*_*ica 4 c# wpf visual-studio-2010

我真的很茫然,并且一直试图找到解决方案几个小时.我搞不清楚了.在我最后一次检查的操作期间,我得到以下异常.

'{DependencyProperty.UnsetValue}' is not a valid value for property 'Foreground'.

我不会把错误发生在哪里.它带我到一个页面,上面写着"No Source Available",没有别的.我已经尝试通过在各个地方放置断点来定位错误,但是在每次运行期间它似乎在不同的点处失败.InnerException为null.

我已经看到了这个问题,以及谷歌的各种文章.我无法弄清楚发生了什么,我不知道如何从这里解决问题.Visual Studio输出似乎没有提供任何更详细的信息,但我会根据请求粘贴它.请,任何帮助表示赞赏.

Cod*_*ked 6

我愿意你缺少资源.如果您执行以下操作:

<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>
Run Code Online (Sandbox Code Playgroud)

然后你会得到这样的例外.我们甚至可以使用ComponentResourceKey来产生这个异常:

<Style TargetType="Button">
    <Setter Property="Foreground" Value="{StaticResource {ComponentResourceKey TypeInTargetAssembly={x:Type FrameworkElement}, ResourceId=NoSuchResourceKey}}" />
</Style>
Run Code Online (Sandbox Code Playgroud)

这里几乎没有什么能够引发这个问题.通常,在使用时,您会收到编译器错误,指出资源不存在StaticResource.比如在这种情况下:

<Button Content="Click Me" Foreground="{StaticResource NoSuchResourceKey}" />
Run Code Online (Sandbox Code Playgroud)

相反,我们做了:

<Button Content="Click Me" Foreground="{StaticResource {ComponentResourceKey TypeInTargetAssembly={x:Type FrameworkElement}, ResourceId=NoSuchResourceKey}}" />
Run Code Online (Sandbox Code Playgroud)

然后你会得到一个不同的异常(XamlParseException),说:

提供'System.Windows.StaticResourceExtension'上的值引发异常.行号"6"和行位置"22".

内部例外:

找不到名为'TargetType = System.Windows.FrameworkElement ID = NoSuchResourceKey'的资源.资源名称区分大小写.

这一切都将我们引向真正的问题(缺少资源).前两个例子没有给我们一个有用的例外的原因是我们没有设置Foreground属性.我们Value在一个Setter对象上设置属性.因此,当找不到资源时,DependencyProperty.UnsetValue使用.这对该Setter.Value物业完全有效.

之后,当Style应用于Button我们获得异常时,因为那DependencyProperty.UnsetValue是实际分配给Button.Foreground属性的时候.

要解决此问题,我将搜索整个解决方案,Property="Foreground"并查找使用不存在的资源的任何实例.

我应该补充说,在使用时不会出现异常DynamicResource,因为传递给Button.Foreground属性的值是"特殊值"(允许延迟查找).除非找到资源,否则此"特殊值"不会分配给定的属性.