获取自定义组件内的相对路径

本文关键字:相对 路径 自定义 组件 获取 | 更新日期: 2023-09-27 18:31:25

我有一个自定义组件项目,我指的是另一个项目。

我需要在自定义组件的页面之间导航,所以我使用以下代码:

var frame = Application.Current.RootVisual as PhoneApplicationFrame;
frame.Navigate(new Uri("/CustomComponent;component/Page.xaml", UriKind.Relative));

现在,假设我的自定义组件具有如下所示的结构:

Root Folder
       '_ Page.xaml
       '_ Folder A
                 '_ BaseClass.cs
       '_ Folder B
                 '_ Folder C
                           '_ Class.cs (extends BaseClass)
                           '_ Page2.xaml

我想调用 Class.cs 内部的一个方法,该方法返回一个字符串,允许我使用我发布的导航代码导航到Page2.xaml

所以,这个方法应该返回

/

自定义组件;组件/文件夹 B/文件夹 C/Page2.xaml

/CustomComponent;component/是可选的,但我需要它返回正确的文件夹结构以导航到页面)

我一直在尝试使用Directory类,但 GetCurrentDirectory() 方法返回指向应用程序安装文件夹的绝对路径,我需要它是遵循组件结构的相对路径。

获取自定义组件内的相对路径

下面是一个函数,用于获取调用函数的绝对路径:

    public static string GetFilePathLoc([CallerFilePath] string filePath = "")
    {
        return filePath;
    }

您可以发布进程以仅提取相对部分,例如,通过创建一个 RootClass 并从中和 Class1 中调用 GetFilePathLoc:

    public abstract class BaseClass
{
    public string GetResourceFilePath()
    {
        string assemblyName = Assembly.GetExecutingAssembly().FullName;
        assemblyName = assemblyName.Substring(0, assemblyName.IndexOf(','));

        string myFilePath = GetRealClassPath();
        //If base class is in the root directory, this could just be replaced by string projectFolder = GetFilePathLoc();
        string projectFolder = RootClass.GetPath();
        //Remove the "absolute part" of the path
        myFilePath = myFilePath.Substring(projectFolder.Length);
         myFilePath=myFilePath.Replace('''', '/');
        return "/" + assemblyName + ",component/" + myFilePath;
    }
    protected abstract string GetRealClassPath();
    protected static string GetFilePathLoc([CallerFilePath] string filePath = "")
    {
        int indexFileName= filePath.LastIndexOf('''');
        return filePath.Substring(0, indexFileName+1);
    }
}

public class Class1 :BaseClass
{
    protected override string GetRealClassPath()
    {
        return GetFilePathLoc(); 
    }
}