【发布时间】:2010-01-22 06:40:30
【问题描述】:
我是 wpf 的新手,我想在 wpf 文本块的一行中显示文本。 例如:
<TextBlock
Text ="asfasfasfa
asdasdasd"
</TextBlock>
TextBlock 默认分两行显示,
但我只希望它出现在像这样“asafsf asfafaf”这样的一行中。我的意思是在一行中显示所有文本,即使文本中有多行
我该怎么办?
【问题讨论】:
我是 wpf 的新手,我想在 wpf 文本块的一行中显示文本。 例如:
<TextBlock
Text ="asfasfasfa
asdasdasd"
</TextBlock>
TextBlock 默认分两行显示,
但我只希望它出现在像这样“asafsf asfafaf”这样的一行中。我的意思是在一行中显示所有文本,即使文本中有多行
我该怎么办?
【问题讨论】:
使用转换器:
<TextBlock Text={Binding Path=TextPropertyName,
Converter={StaticResource SingleLineTextConverter}}
SingleLineTextConverter.cs:
public class SingleLineTextConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string s = (string)value;
s = s.Replace(Environment.NewLine, " ");
return s;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
【讨论】:
而不是这个:
<TextBlock Text="Hello
How Are
You??"/>
使用这个:
<TextBlock>
Hello
How Are
You??
</TextBlock>
或者这个:
<TextBlock>
<Run>Hello</Run>
<Run>How Are</Run>
<Run>You??</Run>
</TextBlock>
或在后面的代码中设置 Text 属性,如下所示:
(In XAML)
<TextBlock x:Name="MyTextBlock"/>
(In code - c#)
MyTextBlock.Text = "Hello How Are You??"
代码隐藏方法的一个优点是您可以在设置文本之前对其进行格式化。 示例:如果从文件中检索文本并且您想要删除任何回车换行符,您可以这样做:
string textFromFile = System.IO.File.ReadAllText(@"Path\To\Text\File.txt");
MyTextBlock.Text = textFromFile.Replace("\n","").Replace("\r","");
【讨论】: