【问题标题】:How to display the text in one line in wpf textblock如何在wpf文本块中显示一行文本
【发布时间】:2010-01-22 06:40:30
【问题描述】:

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

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

TextBlock 默认分两行显示,

但我只希望它出现在像这样“asafsf asfafaf”这样的一行中。我的意思是在一行中显示所有文本,即使文本中有多行
我该怎么办?

【问题讨论】:

    标签: wpf textblock


    【解决方案1】:

    使用转换器:

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

    【讨论】:

    • 这里以转换器源代码为例怎么样?我手边没有 VS,所以无法粘贴。源代码将使其成为最终答案。
    • 喜欢这个想法,谢谢。但是我必须在 Convert() 方法的开头进行一次空值检查,否则我得到一个空引用异常。
    【解决方案2】:

    而不是这个:

                <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","");
    

    【讨论】:

    • 实际上要显示的文本在文件中,所以我不能那样做,还有其他方法吗?非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多