8

私はwpfの初心者です。これは、wpftextblockの1行にテキストを表示したいものです。例えば。:

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

TextBlockは、デフォルトで2行で表示します。

しかし、私はこの「asafsfasfafaf」のように1行だけでそれが欲しいです。つまり、テキストに複数の行がある場合でも、すべてのテキストを1行に表示するには
どうすればよいですか?

4

2 に答える 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();
    }
}
于 2010-01-22T10:39:16.367 に答える
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 プロパティを設定します。

(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","");
于 2010-01-22T07:12:31.530 に答える