wpf 将字符串定义为静态资源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5661127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Define a string as a static resource
提问by Marcom
IS there a way to define a constant string to be used as a static resource across the whole application?
有没有办法定义一个常量字符串作为整个应用程序的静态资源?
I am running a Wpf application but there is no main xaml form. The application is a collection of xaml controls handled by a single classic .cs form.
我正在运行 Wpf 应用程序,但没有主要的 xaml 表单。该应用程序是由单个经典 .cs 表单处理的 xaml 控件的集合。
采纳答案by Damascus
Just add a resource dictionary XAML file, let's say it's named Dictionary.xaml
(Visual Studio can create you one automatically)
只需添加一个资源字典 XAML 文件,假设它已命名Dictionary.xaml
(Visual Studio 可以自动为您创建一个)
Then, add your static resource in this dictionary.
然后,在此字典中添加您的静态资源。
To finish, reference the dictionary in all your XAML controls:
最后,在所有 XAML 控件中引用字典:
<UserControl.Resources>
<ResourceDictionary Source="Dictionary.xaml"/>
</UserControl.Resources>
回答by Felice Pollano
You can define it as an application resource:
您可以将其定义为应用程序资源:
<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>
回答by Henrik
Supplemantary to the answer by @FelicePollano above - for code indentation to work I put this as a separate 'answer'.
对上面@FelicePollano 的回答的补充 - 为了使代码缩进起作用,我将其作为单独的“答案”。
If you happen to have your original constant defined in a .cs-file you can avoid duplicating its value in <Application.Resources>
by this:
如果您碰巧在 .cs 文件中定义了原始常量,则可以<Application.Resources>
通过以下方式避免复制其值:
<x:Static x:Key="MyConstString" Member=local:Constants.MyString />
For the reference ‘local' above to work you need to include the namespace xmlns:local=”clr-namespace:Utils”
in the tag <Application>
.
为了使上面的“本地”引用起作用,您需要xmlns:local=”clr-namespace:Utils”
在标签中包含命名空间 <Application>
。
The cs-class could then look like this:
cs-class 可能如下所示:
namespace Utils
{
public class Constants
{
public const string MyString = “My string”;
}
}
An example on usage in the xaml-code could then be:
在 xaml 代码中使用的一个例子可能是:
<TextBlock Text=”{StaticResource MyConstString}” />
回答by Marcom
I went for this approach although the other answers would work in most cases:
我采用了这种方法,尽管其他答案在大多数情况下都有效:
回答by bafsar
You can use like this:
你可以这样使用:
First, sample constant variable:
一、样本常量变量:
namespace Constants
{
public class ControlNames
{
public const string WrapperGridName = "WrapperGrid";
}
}
And second XAML using:
第二个 XAML 使用:
<TextBlock Text="{x:Static Member=Constants:ControlNames.WrapperGridName}"