programing

wpf TextBlock 컨트롤에 새 줄을 넣는 방법은 무엇입니까?

nasanasas 2020. 8. 31. 07:54
반응형

wpf TextBlock 컨트롤에 새 줄을 넣는 방법은 무엇입니까?


XML 파일에서 텍스트를 가져오고 있으며 텍스트 블록 렌더링에서 새 줄로 해석되는 몇 가지 새 줄을 삽입하고 싶습니다.

난 노력 했어:

<data>Foo bar baz \n baz bar</data>

그러나 데이터는 새 줄없이 계속 표시됩니다. 나는의 내용을 설정 <data>비아 .TextC #을 통해 속성입니다.

GUI에서 새 줄을 렌더링하기 위해 XML에 무엇을 입력해야합니까?

XAML에서 텍스트를 수동으로 설정하는 것과 같은 것을 시도했습니다.

<TextBlock Margin="0 15 0 0" Width="600">
There &#10;
is a new line.
</TextBlock>

인코딩 된 문자는 GUI에 나타나지 않지만 새 줄도 제공하지 않습니다.


데이터에 새 줄을 입력 할 수 있습니다.

<data>Foo bar baz 
 baz bar</data>

작동하지 않으면 문자열을 수동으로 구문 분석해야 할 수 있습니다.

간단한 직접 XAML이 필요한 경우 :

<TextBlock>
    Lorem <LineBreak/>
    Ipsum
</TextBlock>

완전성을 위해 : 다음을 수행 할 수도 있습니다.

 <TextBlock Text="Line1&#x0a;Line 2"/>

바인딩을 사용할 수도 있습니다.

<TextBlock Text="{Binding MyText}"/>

그리고 다음과 같이 MyText를 설정하십시오.

Public string MyText
{
    get{return string.Format("My Text \n Your Text");}
}

당신은 사용해야합니다

 < SomeObject xml:space="preserve" > once upon a time ...
      this line will be below the first one < /SomeObject>

또는 원하는 경우 :

 <SomeObject xml:space="preserve" />  once upon a time... &#10; this line below < / SomeObject>

조심하십시오 : 둘 다 & 10을 사용하고 텍스트의 다음 줄로 이동하면 두 개의 빈 줄이 생깁니다.

자세한 내용은 여기 : http://msdn.microsoft.com/en-us/library/ms788746.aspx


이것은 오래된 질문이지만 방금 문제를 발견하고 주어진 답변과 다르게 해결했습니다. 다른 사람들에게 도움이 될 수 있습니다.

내 XML 파일이 다음과 같음에도 불구하고 알아 차 렸습니다.

<tag>
 <subTag>content with newline.\r\nto display</subTag>
</tag>

내 C # 코드로 읽을 때 문자열에 이중 백 슬래시가 있습니다.

\\r\\n

이 문제를 해결하기 위해 추가 백 슬래시를 제거하는 ValueConverter를 작성했습니다.

public class XmlStringConverter : IValueConverter
{
    public object Convert(
        object value,
        Type targetType,
        object parameter,
        CultureInfo culture)
    {
        string valueAsString = value as string;
        if (string.IsNullOrEmpty(valueAsString))
        {
            return value;
        }

        valueAsString = valueAsString.Replace("\\r\\n", "\r\n");
        return valueAsString;
    }

    public object ConvertBack(
        object value,
        Type targetType,
        object parameter,
        CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

다른 모든 것이 실패하면 다음을 사용할 수도 있습니다.

"My text needs a line break here" + System.Environment.NewLine + " This should be a new line"

<TextBlock Margin="4" TextWrapping="Wrap" FontFamily="Verdana" FontSize="12">
        <Run TextDecorations="StrikeThrough"> Run cannot contain inline</Run>
        <Span FontSize="16"> Span can contain Run or Span or whatever 
            <LineBreak />
        <Bold FontSize="22" FontFamily="Times New Roman" >Bold can contains 
            <Italic>Italic</Italic></Bold></Span>
</TextBlock>

System.Environment.NewLine을 사용하는 것이 나를 위해 일한 유일한 솔루션입니다. \ r \ n 시도했을 때 텍스트 상자에서 실제 \ r \ n을 반복했습니다.


텍스트 블록에이 옵션이 활성화되어 있는지 확인해야합니다.

AcceptsReturn="True"

Insert a "line break" or a "paragraph break" in a RichTextBox "rtb" like this:

var range = new TextRange(rtb.SelectionStart, rtb.Selection.End); 
range.Start.Paragraph.ContentStart.InsertLineBreak();
range.Start.Paragraph.ContentStart.InsertParagraphBreak();

The only way to get the NewLine items is by inserting text with "\r\n" items first, and then applying more code which works on Selection and/or TextRange objects. This makes sure that the \par items are converted to \line items, are saved as desired, and are still correct when reopening the *.Rtf file. That is what I found so far after hard tries. My three code lines need to be surrounded by more code (with loops) to set the TextPointer items (.Start .End .ContentStart .ContentEnd) where the Lines and Breaks should go, which I have done with success for my purposes.

참고URL : https://stackoverflow.com/questions/8525396/how-to-put-a-new-line-into-a-wpf-textblock-control

반응형