c# - 如何在 Binding StringFormat 中使用变量文本?

标签 c# wpf xaml binding string-formatting

所以我想在绑定(bind)中有一个变量 StringFormat,但我不知道如何做到这一点。我不介意它是 XAML 还是代码隐藏。这是我目前拥有的:

<TextBlock x:Name="TextBlockSpellSkill" Text="{Binding CurrentValue, StringFormat=Spell: {0}}" />

但是,我希望能够根据模型中的变量将前缀“Spell:”更改为“Skill:”。最简单的方法是如果我可以在类似这样的代码后面做到这一点:

if (true)
{
    TextBlockSpellSkill.StringFormat = "Spell: {0}";
}
else
{
    TextBlockSpellSkill.StringFormat = "Skill: {0}";
}

但我找不到任何方法来从代码隐藏中设置字符串格式。如果有一种在 XAML 中实现这一点的好方法,我也很乐意!

谢谢

最佳答案

您使用的StringFormat用于Binding。你想做的是这样的事情

var textBlock = new TextBlock();
var binding = new Binding("CurrentValue");
binding.StringFormat = "Spell : {0}";
textBlock.SetBinding(TextBlock.TextProperty, binding);

关于c# - 如何在 Binding StringFormat 中使用变量文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24518403/

相关文章:

c# - 如何将 C# 类公开为 com 对象接口(interface)?

c# - 如何在 wpf 应用程序中使用 mshtml

c# - 如何使用 MVVM 模式避免对数据库进行多余的第二次查询?

c# - WPF 列表框选择已更改 MVVM

c# - 如何将图像分成 9 block 并随机放置在 Canvas 中?

c# - 在 xaml 中设置样式或格式化 json 数据

c# - Xamarin Android TextColor 属性在不同设备上表现异常

c# - 使用 WPF WebBrowser 控件进行拖放 - 放置事件未触发

c# - LINQ to SQL 多表左外连接

wpf - 如何在 WPF DataGrid 中实现多列 ComboBox DataGridColumn?