How to display the text in one line in wpf textblock

我的未来我决定 提交于 2019-12-30 08:36:39

问题


I'm a newbie with wpf , what i want to display the text in one line in wpf textblock. eg.:

<TextBlock 
    Text ="asfasfasfa
    asdasdasd"
</TextBlock>

TextBlock display it in two lines default,

but i want it in only one line like this"asafsf asfafaf". I mean show all the text in one line even there are more than one lines in the text
what should i do?


回答1:


Use a Converter:

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



回答2:


Instead of this:

            <TextBlock Text="Hello
                How Are
                You??"/>

Use this:

            <TextBlock>
                Hello
                How Are
                You??
            </TextBlock>

or this:

            <TextBlock>
                <Run>Hello</Run> 
                <Run>How Are</Run> 
                <Run>You??</Run>
            </TextBlock>

or set Text property in code behind like this :

(In XAML)

            <TextBlock x:Name="MyTextBlock"/>

(In code - c#)

            MyTextBlock.Text = "Hello How Are You??"

Code-behind approach has an advantage that you can format your text before setting it. Example: If the text is retrieved from a file and you want to remove any carriage-return new-line characters you can do it this way:

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


来源:https://stackoverflow.com/questions/2115520/how-to-display-the-text-in-one-line-in-wpf-textblock

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!