wpf Stringformat 连接数据绑定和资源的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11852050/
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
Stringformat concatenates databinding and resource's value
提问by Louro
I want to concatenate in my window title a property from my viewmodel and a value that cames from a resources file. This is what I have working without the string from resources:
我想在我的窗口标题中连接来自我的视图模型的属性和来自资源文件的值。这是我在没有资源字符串的情况下所做的工作:
Title="Binding Path=Description, StringFormat=Building: {0}}"
Now I want to remove the "Building" string and put a value from a resource like I use on other places:
现在我想删除“Building”字符串并从资源中放置一个值,就像我在其他地方使用的一样:
xmlns:res="clr-namespace:Project.View.Resources"
{res:Strings.TitleDescription}
How can I define both? Can I define like a {1} parameter?
我如何定义两者?我可以像 {1} 参数一样定义吗?
回答by madd0
Yes, you can. Simply use a MultiBinding.
是的你可以。只需使用一个MultiBinding.
The MSDN article on StringFormathas an example.
MSDN上的文章StringFormat有一个例子。
In your case, the code would look something like this:
在您的情况下,代码如下所示:
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} {1}">
<Binding Source="{x:Static res:Strings.TitleDescription}"/>
<Binding Path="Description"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
回答by Mike Fuchs
I've seen the MultiBindinganswer in several places now, and it is almost never necessary to use it. You can define your resource as the string format instead, and as long as there is only one string format argument, no MultiBindingis required. Makes the code a lot more succinct:
我现在已经MultiBinding在好几个地方看到了答案,几乎没有必要使用它。您可以将资源定义为字符串格式,只要只有一个字符串格式参数,MultiBinding就不需要。使代码更加简洁:
<TextBlock Text="{Binding Description, StringFormat={x:Static res:Strings.TitleDesc}}" />
And the TitleDescresource is obviously "Building: {0}".
而且TitleDesc资源很明显"Building: {0}"。

