WPF 应用程序中的相对路径

Relative paths in WPF applications

我正在 VS2013 中编写此 WPF 应用程序,但我无法弄清楚如何将我的绝对路径转换为相对路径。

该应用涉及在特定操作发生时更改网格背景。我目前是这样处理的:

ImageBrush b1 = new ImageBrush();
b1.ImageSource = new BitmapImage(new Uri(@"C:\Users\spectre\Documents\Visual Studio 2013\Projects\eGym v2\eGym v1\eGym v1\resources\example.jpg"));
grid1.Background = b1;

我想弄清楚如何在不改变程序结构的情况下将绝对路径变成相对路径,但即使环顾了几个小时,现在我似乎也做不对。

您可以将图像添加到您的解决方案中并像这样引用它:

b1.ImageSource = new BitmapImage(new Uri(@"..\Image\example.jpg"));

这种方法在使用 PrismMVVM Light:

的 WPF 应用程序中节省了我的时间
var myBrush = new ImageBrush();
var image = new Image{
     Source = new BitmapImage(new Uri("pack://application:,,,/YourApplicationName;component/Images/example.jpg"))};
myBrush.ImageSource = image.Source;
grid1.Background = myBrush;