您可以在 XAML 属性数据绑定期间对超链接的 NavigateUri 属性进行 StringFormat 吗?
作为 WPF 数据绑定的一部分,是否有一种简单的方法来转换或格式化字符串?
假设我想创建一个基于字符串标记的 WPF 超链接元素。
<Hyperlink NavigateUri="{Binding Tag}">
<Run Text="{Binding Tag}" />
</Hyperlink>
但我需要首先转换 NavigateUri 属性的 Tag,使其成为真正的超链接或 PackUri。
例如,如果我的标签是“folksonomy”,我想创建一个如下字符串:http://www.example.com/tags/tagview?tag=folksonomy
实现的最佳方法是什么这? XAML中有字符串操作函数吗?我必须写一个转换器吗?我是否必须构建一个完整的单独的 ViewModel 类才能进行一些字符串格式化?
更新:超链接元素似乎出现了一些奇怪的情况。我可以获得答案中建议的 StringFormat 语法,适用于普通 TextBlock 的 Text 属性,但不适用于超链接的 NavigateUri 属性。
正如一个答案指出的,这可能是因为 NavigateUri 属性正式采用 Uri,而不是字符串。显然需要自定义转换器或 ViewModel 属性。
Is there an easy way to transform or format a string as part of WPF data binding?
Suppose I want to create a WPF Hyperlink element based on a string tag.
<Hyperlink NavigateUri="{Binding Tag}">
<Run Text="{Binding Tag}" />
</Hyperlink>
But I need to transform the Tag first for the NavigateUri property to make it a true hyperlink or PackUri.
For instance, if my tag were "folksonomy" I'd want to create a string like: http://www.example.com/tags/tagview?tag=folksonomy
What's the best way to achieve this? Is there a string manipulation function in XAML? Do I have to write a converter? Do I have to build a whole separate ViewModel class just to do a little string formatting?
UPDATE: There appears to be something strange going on with the Hyperlink element. I can get the StringFormat syntax suggested in the answers to work for the Text property of an ordinary TextBlock, but not for the NavigateUri property of a Hyperlink.
As one answer noted, this is likely due to the fact that the NavigateUri property officially takes a Uri, not a string. Apparently a custom converter or ViewModel property will be required.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用绑定的字符串格式化功能:
You can use the string formatting capabilities of bindings:
正如 Kent 所说,假设您使用的是 .NET 3.5 SP1(字符串格式已作为 SP1 的一部分添加),您可以使用字符串格式。这里有很好的示例: http://blogs.msdn.com/b/llobo/archive/2008/05/19/wpf-3-5-sp1-feature-stringformat.aspx
如果您使用的不是 .NET 3.5 SP1 或字符串格式方法变得太混乱,您可能需要一个 IValueConverter http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx
Like Kent said you can use string formatting assuming you are on .NET 3.5 SP1 (string formatting was added as part of SP1). Good Samples here: http://blogs.msdn.com/b/llobo/archive/2008/05/19/wpf-3-5-sp1-feature-stringformat.aspx
If you aren't on .NET 3.5 SP1 or the string format approach becomes too messy you would want to us an IValueConverter http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx
对于任何其他偶然发现此线程寻求解决方案的人,我发现 Foovanadil 建议的 IValueConverter 对我来说效果很好。
使用我的代码隐藏中的转换器类:
For anyone else stumbling across this thread seeking a solution, I found Foovanadil's suggested IValueConverter worked well for me.
With the converter class in my codebehind: