私はwpfの初心者です。これは、wpftextblockの1行にテキストを表示したいものです。例えば。:
<TextBlock
Text ="asfasfasfa
asdasdasd"
</TextBlock>
TextBlockは、デフォルトで2行で表示します。
しかし、私はこの「asafsfasfafaf」のように1行だけでそれが欲しいです。つまり、テキストに複数の行がある場合でも、すべてのテキストを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();
}
}
これの代わりに:
<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","");