如何在 XAML 中使用资源中的值和绑定中的一个值来格式化字符串?

Deb*_*ere 3 .net c# windows wpf xaml

我需要开发一个支持本地化的应用程序,因此我需要TextBlock以这样一种方式格式化 a:字符串的一部分从绑定中获取一个参数,一部分从资源中获取。我是这样写的

<TextBlock Height="30" >
    <TextBlock.Text>
        <MultiBinding  StringFormat="{}{0} -- *Now only* {1:C}!">
            <Binding Path="Description"/>
            <Binding Path="Price"/>
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)

现在这只是我需要从资源字符串中获取的部分。该字符串位于资源中,但我不知道如何以这种方式创建该字符串。任何人都可以帮助我吗?

我知道使用转换器是一个解决方案,但我有很多这样的场景,因此我最终可能会得到多个转换器,这不是一个好主意。我相信使用StringFormat我可以实现它。但我缺少一些东西。

sa_*_*213 5

您可以添加对资源命名空间的引用,然后向您的多绑定添加另一个绑定

示例(未经测试)

   xmlns:p="clr-namespace:MyApplication.Properties"

   <TextBlock Height="30" >
        <TextBlock.Text>
            <MultiBinding  StringFormat="{}{0} -- {2} {1:C}!">
                <Binding Path="Description"/>
                <Binding Path="Price"/>

                <Binding Path="{x:Static p:Resources.Nowonly}"/>
                <!-- Or possibly Source instaed of Path as mentioned by @dkozl -->
                <Binding Source="{x:Static p:Resources.Nowonly}"/>
            </MultiBinding>
        </TextBlock.Text>
    </TextBlock>
Run Code Online (Sandbox Code Playgroud)

  • 尝试 `{Binding Source="{x:Static p:Resources.Nowonly}`。注意 `Source` 而不是 `Path` (3认同)