如何在WPF TextBlock中将文本显示在一行中

8
我是一个wpf新手,我想在wpf textblock中将文本显示在一行中。 例如:
<TextBlock 
    Text ="asfasfasfa
    asdasdasd"
</TextBlock>

默认情况下,TextBlock会将文本显示在两行中,

但我想要像这样只显示一行:“asafsf asfafaf”。也就是说,即使文本有多行,也要在一行中显示所有文本。
我该怎么办?

2个回答

17

使用转换器:

    <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();
    }
}

1
如果您能在此处提供转换器的源代码作为示例,那会怎么样呢?我手边没有VS,所以无法复制粘贴。源代码将使这成为最权威的答案。 - Thorsten79
1
喜欢这个想法,谢谢。但是我不得不在Convert()方法的开头进行空值检查,否则会出现空引用异常。 - nightcoder

5

不要这样写:

            <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 属性:
(在 XAML 中)
            <TextBlock x:Name="MyTextBlock"/>

(在代码中 - 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","");

实际上要显示的文本在文件中,所以我不能这样做,还有其他方法吗?非常感谢。 - baorui

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接