Xaml中的静态字符串

4

我有一个包含一些静态信息的类,即:

public static class MyApp
{
    public static string Name = "Awesome App";
    public static string Version = "1.0";
}

我希望在我的应用程序中任何显示应用名称的地方都使用这个字符串,但问题是有些地方不止一个变量字符串。

例如:

<TextBlock Text="Awesome App running version 1.0"/>

我希望这些内容可以从静态变量中填充。我已经阅读了一些资料,并看到了几个选项:

1. 使用 MultiBinding 并加载相关的 ResourceDictionary

<ResourceDictionary>
    <sys:String x:Key="AppName">Awesome App</sys:String>
    <sys:String x:Key="AppVersion">1.0</sys:String>
</ResourceDictionary>

<TextBlock>
    <TextBlock.Text>
        <MultiBinding StringFormat="{}{0} running version {1}">
            <Binding Path="{StaticResource AppName}"/>
            <Binding Path="{StaticResource AppVersion}"/>
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

我想我也可以有多个TextBlock

<TextBlock>
    <TextBlock Text="{StaticResource AppName}"/>
    <TextBlock Text=" running version "/>
    <TextBlock Text="{StaticResource AppVersion}"/>
<TextBlock>

2. 使用静态 "strings" 类和静态属性:

public static class Strings
{
    public static string ProductRunningVersion =>
        $"{MyApp.Name} running version {MyApp.Version}";
}

<TextBlock Text="{x:Static local:Strings.ProductRunningVersion}"/>

=> 在属性中的使用是有意为之的 - 在测试时,我遇到了一些静态变量初始化顺序的问题。(有些是通过静态构造函数进行初始化)


我不确定哪种方法更好。 第一种方法感觉更加“正式”,但也很混乱。 第二种方法感觉要干净得多,但与我在WPF中习惯的方式不太一样。而且,必须将字符串定义为get函数而不是静态字符串,这会带来一些成本吗?

这两种方法都可以吗?我并不是真的要进行本地化,只是要在整个应用程序中更改名称和一些图像。


2
第一种方法更好,因为它是逻辑的,而且是基于纯标记语言的。在第一种方法的下一个子方法中,用Run替换内部的TextBlocks - AnjumSKhan
1个回答

3

所有的方法都是有效的。使用最适合你的方法。我有几点评论:

  • You don't have to add the strings to a ResourceDictionary; you can use x:Static to access constants as well:

    <TextBlock>
        <TextBlock.Text>
            <MultiBinding StringFormat="{}{0} running version {1}">
                <Binding Source="{x:Static local:MyApp.Name}"/>
                <Binding Source="{x:Static local:MyApp.Version}"/>
            </MultiBinding>
        </TextBlock.Text>
    </TextBlock>
    
  • A TextBlock uses Inlines (which is a lightweight content element) to render text, the most basic of which is a Run. If you want to build a complex TextBlock, you should use those, and not add other TextBlocks (which are full-fledged controls). So, to use your example:

    <TextBlock>
        <Run Text="{x:Static local:MyApp.Name}"/>
        <Run Text=" running version "/>
        <Run Text="{x:Static local:MyApp.Version}"/>
    <TextBlock>
    

    I would prefer this approach to the MultiBinding. Here, for example, you can even add elements such as <Bold> and <Hyperlink> to render formatted text.


+1. 一个带有RunsTextBlock是最好、最简单和最清晰的解决方案,甚至可以缩短代码,因为在TextBlock内部的原始文本元素会自动被视为Runs<TextBlock><Run Text="{x:Static local:MyApp.Name}"/> 运行中 <Run Text="{x:Static local:MyApp.Version}"/> - Avner Shahar-Kashtan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接