为什么我的 wpf 表单绑定到内部资源?

Why does my wpf form bind to internal resource?

我有一个 wpf 控件和一个资源(标记为内部)- 都在同一个命名空间中。

但是当我尝试通过

访问资源时
   <Window x:Class="WpfApp7.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp7"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <TextBlock Text="{x:Static local:Resource1.String1}" />
    </Grid>
   </Window>

我收到运行时 XamlParseException。一旦我创建资源 public,一切正常。

我是否被迫让资源 public 从 xaml 访问它?在后台 c# 代码中,一切正常。

编辑: 内部 ArgumentException 异常表明,静态值 "WpfApp7.Resource1.String1" 无法解析为枚举、静态字段或 属性.

你必须明白,{x:static}是一个标记扩展,只是用来在运行时用XAML解析Member 属性 - 服务,它们被放置在另一个组件中。请参阅 MSDN 上的 x:Static Markup Extension

You can make x:Static references to static fields or properties that are not in the default XAML namespace for the current XAML document; however, this requires a prefix mapping. XAML namespaces are almost always defined on the root element of the XAML document.

The lookup operations for static properties can be performed by .NET XAML Services and its XAML readers and XAML writers, when they are running with the default XAML schema context.

所以

<TextBlock Text="{x:Static local:Resource1.String1}" />

等同于:

<TextBlock Text="{x:Static Member=local:Resource1.String1}" />

由于内部 属性 无法解析关于必须抛出 Member 内容的默认错误消息:

The code entity that is referenced must be one of the following:

  • A constant
  • A static property
  • A field
  • An enumeration value

Specifying any other code entity, such as a nonstatic property, causes a compile-time error if the XAML is markup compiled, or a XAML load-time parse exception.