由于无法找到资源,UserControl将不会在设计时呈现?

Dan*_*iel 5 wpf xaml

我有一个非常简单的WPF项目设置如下:

在此输入图像描述

MyFoo.xaml看起来像:

<UserControl xmlns:bar="clr-namespace:WpfApplication1.UserControls" ...>
  <Grid>
    <bar:MyUserControl />
  </Grid>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

Styles.xaml看起来像:

<Style TargetType="TextBlock">
  <Setter Property="Foreground"
          Value="Red" />
</Style>
Run Code Online (Sandbox Code Playgroud)

MyUserControl.xaml看起来像:

<UserControl.Resources>
  <ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
      <ResourceDictionary Source="/Styles/Styles.xaml" />
    </ResourceDictionary.MergedDictionaries>
  </ResourceDictionary>
</UserControl.Resources>
<Grid>
  <TextBlock Text="Hello world!" />
</Grid>
Run Code Online (Sandbox Code Playgroud)

我的控件不会在设计时呈现,但它在运行时工作正常:

在此输入图像描述 在此输入图像描述

如截图所示,我收到错误:

找不到资源'styles/styles.xaml'.

我已经尝试将Styles.xaml的构建操作设置为"资源"和清理/构建,但它不起作用.

为什么会这样?我如何解决它?

Kcv*_*vin 6

我能够复制这个问题。

背后的道理是:

xmlns:bar="clr-namespace:WpfApplication1.UserControls"
Run Code Online (Sandbox Code Playgroud)

您专门为 UserControls 指定命名空间。由于您尝试合并MyUserControl使用位置 ( Source) 指定源的字典,因此它可以找到资源;然而 Foo.MyFoo 似乎不知道去哪里查看。无论设计器尝试在 MyFoo 中实例化 MyUserControl 时发生什么情况,它都无法解析 Styles.xaml 资源的位置。

要解决这个问题,

  1. 将您的Styles文件夹 +Styles.xaml拖入UserControls文件夹。
  2. MyUserControl.xaml您的源路径修复为<ResourceDictionary Source="Styles/Styles.xaml" />

您现在可以在设计时看到您的控件。

编辑

我找到了一种方法来保持项目原样并获得相同的结果。

  1. 将 Styles.xaml 构建操作设置为资源。
  2. 更改Source/WpfApplication1;component/Styles/Styles.xaml
  3. 重建

至于构建操作之间的差异,这里有一篇很好的文章。

在 VS2012 中,我得到了异常的 StackTrace,最低级别似乎可能相关Baml(当 Build Action 设置为 Page 时创建 Baml)。这是最内部的异常:

IOException: Cannot locate resource 'styles/styles.xaml'.    at
    MS.Internal.AppModel.ResourcePart.GetStreamCore(FileMode mode,
    FileAccess access)    at
    System.IO.Packaging.PackagePart.GetStream(FileMode mode, FileAccess
    access)    at
    System.IO.Packaging.PackWebResponse.CachedResponse.GetResponseStream()
    at System.IO.Packaging.PackWebResponse.GetResponseStream()    at
    System.IO.Packaging.PackWebResponse.get_ContentType()    at
    MS.Internal.WpfWebRequestHelper.GetContentType(WebResponse response)  
    at MS.Internal.WpfWebRequestHelper.GetResponseStream(WebRequest
    request, ContentType& contentType)    at
    System.Windows.ResourceDictionary.set_Source(Uri value)    at
    System.Windows.Baml2006.WpfSharedBamlSchemaContext.       <Create_BamlProperty_ResourceDictionary_Source>b__1c4(Object
    target, Object value)    at
    System.Windows.Baml2006.WpfKnownMemberInvoker.SetValue(Object
    instance, Object value)    at
    MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(XamlMember member,
    Object obj, Object value)    at
    MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(Object inst,
    XamlMember property, Object value)
Run Code Online (Sandbox Code Playgroud)