如何在wpf文本块中的一行中显示文本

bao*_*ui 7 wpf textblock

我是wpf的新手,我想在wpf文本块中的一行显示文本.例如.:

<TextBlock 
    Text ="asfasfasfa
    asdasdasd"
</TextBlock>
Run Code Online (Sandbox Code Playgroud)

TextBlock默认显示两行,

但我只想在一行中像"asafsf asfafaf"一样.我的意思是在一行中显示所有文本,即使文本中有多行,
我该怎么办?

Kis*_*mar 16

使用转换器:

    <TextBlock Text={Binding Path=TextPropertyName,
Converter={StaticResource SingleLineTextConverter}}
Run Code Online (Sandbox Code Playgroud)

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();
    }
}
Run Code Online (Sandbox Code Playgroud)


mg0*_*007 6

而不是这个:

            <TextBlock Text="Hello
                How Are
                You??"/>
Run Code Online (Sandbox Code Playgroud)

用这个:

            <TextBlock>
                Hello
                How Are
                You??
            </TextBlock>
Run Code Online (Sandbox Code Playgroud)

或这个:

            <TextBlock>
                <Run>Hello</Run> 
                <Run>How Are</Run> 
                <Run>You??</Run>
            </TextBlock>
Run Code Online (Sandbox Code Playgroud)

或在后面的代码中设置Text属性,如下所示:

(In XAML)

            <TextBlock x:Name="MyTextBlock"/>
Run Code Online (Sandbox Code Playgroud)

(In code - c#)

            MyTextBlock.Text = "Hello How Are You??"
Run Code Online (Sandbox Code Playgroud)

代码隐藏方法的优势在于您可以在设置之前格式化文本.示例:如果从文件中检索文本并且您要删除任何回车换行符,则可以这样做:

 string textFromFile = System.IO.File.ReadAllText(@"Path\To\Text\File.txt");
 MyTextBlock.Text = textFromFile.Replace("\n","").Replace("\r","");
Run Code Online (Sandbox Code Playgroud)