XAML 将字符串定义为静态资源

mnemlml8  于 2022-12-07  发布在  其他
关注(0)|答案(4)|浏览(179)

有没有办法定义一个常量字符串,将其用作整个应用程序的静态资源?
我正在运行一个Wpf应用程序,但没有主xaml窗体。该应用程序是由单个classic .cs窗体处理的xaml控件的集合。

e0bqpujr

e0bqpujr1#

您可以将其定义为应用程序资源:

<Application x:Class="xxxxxx"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:clr="clr-namespace:System;assembly=mscorlib"
                 StartupUri="MainWindow.xaml">
        <Application.Resources>
            <clr:String x:Key="MyConstString">My string</clr:String>
        </Application.Resources>
    </Application>
dly7yett

dly7yett2#

作为answer by @FelicePollano的补充-为了使代码缩进工作,我把它作为一个单独的“答案”。
如果您碰巧在. cs文件中定义了原始常量,则可以通过以下方式避免在<Application.Resources>中复制其值:

<x:Static x:Key="MyConstString" Member="local:Constants.MyString" />

要使上面的引用local起作用,您需要在标记<Application>中包含名称空间xmlns:local="clr-namespace:Utils"
这样,cs类就可以如下所示:

namespace Utils 
{
    public class Constants
    {
        public const string MyString = "My string";
    }
}

在xaml代码中的用法示例如下:

<TextBlock Text="{StaticResource MyConstString}" />
vhipe2zx

vhipe2zx3#

只需添加一个资源字典XAML文件,假设它的名称为Dictionary.xaml(Visual Studio可以自动为您创建一个)
然后,在此字典中添加静态资源。
若要完成,请在所有XAML控件中引用该词典:

<UserControl.Resources>
                <ResourceDictionary Source="Dictionary.xaml"/>
    </UserControl.Resources>
kx1ctssn

kx1ctssn4#

您可以这样使用:
一、样本常量变量:

namespace Constants
{
    public class ControlNames
    {
        public const string WrapperGridName = "WrapperGrid";
    }
}

第二个XAML使用:

<TextBlock Text="{x:Static Member=Constants:ControlNames.WrapperGridName}"

相关问题