Rhy*_*hys 23 data-binding wpf xaml textblock
我想将文本添加到绑定到文本块的结果中:
<TextBlock Text="{Binding Title}" Foreground="#FFC8AB14" FontSize="28" />
Run Code Online (Sandbox Code Playgroud)
显示的文字是:
" My title "
Run Code Online (Sandbox Code Playgroud)
我想要的是:
This is "My title"
Run Code Online (Sandbox Code Playgroud)
She*_*bin 43
您可以使用StringFormat绑定的属性:
<TextBlock Text="{Binding Title, StringFormat=This is {0}}"></TextBlock>
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请查看此博客文章:XAML中的WPF String.Format,带有StringFormat属性.
如果你想在绑定中这样做:
<TextBlock Foreground="#FFC8AB14" FontSize="28">
<TextBlock.Text>
<Binding Path="Title">
<Binding.StringFormat>
This is "{0}"
</Binding.StringFormat>
</Binding>
</TextBlock.Text>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)
转义引号所需的元素语法.如果引号只是为了标记插入的文本而不应该出现在输出中,那么当然要容易得多:
<TextBlock Text="{Binding Title, StringFormat={}This is {0}}" Foreground="#FFC8AB14" FontSize="28">
Run Code Online (Sandbox Code Playgroud)
您可以使用转换器来完成此操作。
<TextBlock Text="{Binding Title, ConverterParameter=This is, Converter={StaticResource TextPrefixConverter}}" Foreground="#FFC8AB14" FontSize="28" />
Run Code Online (Sandbox Code Playgroud)
转换器只需在绑定值前添加 ConverterParameter 前缀即可。
public class TextPrefixConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
String result = String.Empty;
if ( parameter != null)
result = parameter.ToString( );
if (value != null)
result += value.ToString( );
return result;
}
...
}
Run Code Online (Sandbox Code Playgroud)
空格和/或引号是否应该成为输出的一部分并不明显。如果是这样,可以更改转换器以修剪空格和/或向构造的字符串添加引号。
另一种方法是:
<TextBlock Foreground="#FFC8AB14" FontSize="28" >
<Run Text="This is " />
<Run Text="{Binding Path=Title}" />
</TextBlock>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21122 次 |
| 最近记录: |