方法: TextWrapping プロパティをプログラムにより変更する

次のコード例では、TextWrapping プロパティの値をプログラムで変更する方法を示しています。

3 つの Button 要素は、XAML の StackPanel 要素に配置されます。 Button の各 Click イベントは、そのコードのイベント ハンドラーに対応します。 イベント ハンドラーは、ボタンがクリックされると txt2 に適用される、TextWrapping 値と同じ名前を使用します。 また、(XAML にはない TextBlock である) txt1 のテキストが更新され、プロパティが変わったことが反映されます。

<StackPanel Orientation="Horizontal" Margin="0,0,0,20">
  <Button Name="btn1" Background="Silver" Width="100" Click="Wrap">Wrap</Button>
  <Button Name="btn2" Background="Silver" Width="100" Click="NoWrap">NoWrap</Button>
  <Button Name="btn4" Background="Silver" Width="100" Click="WrapWithOverflow">WrapWithOverflow</Button>
</StackPanel>

<TextBlock Name="txt2" TextWrapping="Wrap" Margin="0,0,0,20" Foreground="Black">
  Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Lorem ipsum dolor sit amet, 
  consectetuer adipiscing elit.Lorem ipsum dolor sit aet, consectetuer adipiscing elit.
  Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
</TextBlock>
private void Wrap(object sender, RoutedEventArgs e)
{
    txt2.TextWrapping = System.Windows.TextWrapping.Wrap;
    txt1.Text = "The TextWrap property is currently set to Wrap.";
}
private void NoWrap(object sender, RoutedEventArgs e)
{
    txt2.TextWrapping = System.Windows.TextWrapping.NoWrap;
    txt1.Text = "The TextWrap property is currently set to NoWrap.";
}
private void WrapWithOverflow(object sender, RoutedEventArgs e)
{
    txt2.TextWrapping = System.Windows.TextWrapping.WrapWithOverflow;
    txt1.Text = "The TextWrap property is currently set to WrapWithOverflow.";
}
Private Sub Wrap(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)
    txt2.TextWrapping = System.Windows.TextWrapping.Wrap
    txt1.Text = "The TextWrap property is currently set to Wrap."
End Sub

Private Sub NoWrap(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)
    txt2.TextWrapping = System.Windows.TextWrapping.NoWrap
    txt1.Text = "The TextWrap property is currently set to NoWrap."
End Sub

Private Sub WrapWithOverflow(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)
    txt2.TextWrapping = System.Windows.TextWrapping.WrapWithOverflow
    txt1.Text = "The TextWrap property is currently set to WrapWithOverflow."
End Sub

参照