C# 从资源文件中引用资源密钥

C# 从资源文件中引用资源密钥,c#,wpf,resourcedictionary,C#,Wpf,Resourcedictionary,我曾经有一个WinForms应用程序,其中我使用一个静态类来获取简单的字符串资源。在这个类中,我可以访问常量字符串。其中一个字符串由另一个常量的值加上它自己的值组成。大概是这样的: private const string Path = @"C:\SomeFolder\"; public const string FileOne = Path + "FileOne.txt"; public const string FileTwo = Path + "FileTwo.txt"; 现在我有了一个

我曾经有一个WinForms应用程序,其中我使用一个静态类来获取简单的字符串资源。在这个类中,我可以访问常量字符串。其中一个字符串由另一个常量的值加上它自己的值组成。大概是这样的:

private const string Path = @"C:\SomeFolder\";
public const string FileOne = Path + "FileOne.txt";
public const string FileTwo = Path + "FileTwo.txt";
现在我有了一个WPF应用程序,我正在使用一个ResourceDictionary,我将它合并到了应用程序范围中。一切正常,但我想要类似上面的C代码。这是我已经拥有的:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:System="clr-namespace:System;assembly=mscorlib">

    <System:String x:Key="Path">C:\SomeFolder\</System:String>
    <System:String x:Key="FileOne">FileOne.txt</System:String>
    <System:String x:Key="FileTwo">FileTwo.txt</System:String>

</ResourceDictionary>

C:\SomeFolder\
FileOne.txt
FileTwo.txt
现在我需要一些自动添加到两个文件字符串中的东西(对“Path”的某种引用),它不需要像C代码中那样是私有的。有人知道我怎样才能做到这一点吗


提前谢谢

您仍然可以使用带有资源的静态类:

namespace WpfStaticResources
{
    class MyResources {
        private const string Path = @"C:\SomeFolder\";
        public const string FileOne = Path + "FileOne.txt";
        public const string FileTwo = Path + "FileTwo.txt";
    }
}
然后从您的XAML引用中可以看出:

<Window x:Class="WpfStaticResources.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:WpfStaticResources="clr-namespace:WpfStaticResources" 
    Title="{x:Static WpfStaticResources:MyResources.FileOne}" Height="350" Width="525">
    <Grid>

    </Grid>
</Window>


就我个人而言,我不喜欢使用静态类,而是创建一个域对象,将其设置为DataContext,然后绑定到其上的属性。

如果您想在XAML中使用它,这里有两个建议:

想法1:one
绑定

在您的资源中,仅添加
路径

<System:String x:Key="Path">C:\SomeFolder\</System:String>
这就是你所需要的


或者,如果您不在UI中使用这些
字符串
s,您仍然可以使用静态类。但是使用XAML方法更干净(所有与UI相关的东西都应该留在XAML中)

在我的WPF应用程序中,我从一个静态类开始,就像你建议的那样。但我想使用ResourceDictionary,因为这就是它的用途。但是谢谢你的考虑!;)
<TextBlock Text='{Binding Source={StaticResource Path}, StringFormat={}{0}FileOne.txt}' />
    <TextBlock >
        <TextBlock.Text>
            <MultiBinding StringFormat="{}{0}{1}">
                <Binding Source="{StaticResource Path}" />
                <Binding Source="{StaticResource FileOne}" />
            </MultiBinding>
        </TextBlock.Text>
    </TextBlock>