使用项目中的图像文件作为资源

Using a image file in a project as a resource

我需要使用项目内 res 文件夹中的图像,就像资源一样,但在项目编译过程中,出现异常,如“System.IO.IOException”,描述为“资源” res/rook.png" 找不到。".

chessField = new ChessField();
chessField.fillField();
for (int i = 0; i < 64; i++)
{
  Border border = new Border();
  border.Background = i % 2 == 0 ? Brushes.White : Brushes.Black;
  Image chessPiece = new Image();
  string pngFileName;
  if (chessField.Field[i / 8, i % 8] != null) 
  {
    pngFileName = chessField.Field[i / 8, i % 8].pieceType.ToString().ToLower();
    chessPiece.Source = new BitmapImage(
        new Uri($"pack://application:,,,/ChessWPF;component/res/{pngFileName}.png",
        UriKind.RelativeOrAbsolute));
  }
  border.Child = chessPiece;
  xamlField.Children.Add(border);
}

new Uri($"pack://application:,,,/ChessWPF;component/res/{pngFileName}.png"

行出现异常

我只需打开 png 文件的属性并在“生成操作”字段中将它们标记为资源。