Share via


How to: Change the TextWrapping Property Programmatically

Example

The following code example shows how to change the value of the TextWrapping property programmatically using Microsoft Visual Basic .NET.

Four Buttons are placed within a StackPanel element in Extensible Application Markup Language (XAML). Each Button's  Click event corresponds with a subprocedure defined in the Microsoft Visual Basic .NET code, below. After the TextWrapping value associated with each event is invoked, the TextBlock identified by the Name  txt2 is updated to reflect the change in the property.

<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>

The events associated with the Button clicks defined above are handled in Microsoft Visual Basic .NET Sub procedures. Each Click changes the value of the TextWrapping property to the value specified in the procedure and updates the element txt1 to reflect the change in the property.

public void Wrap(object sender, RoutedEventArgs e)
{
    txt2.TextWrapping = System.Windows.TextWrapping.Wrap;
    txt1.Text = "The TextWrap property is currently set to Wrap.";
}
public void NoWrap(object sender, RoutedEventArgs e)
{
    txt2.TextWrapping = System.Windows.TextWrapping.NoWrap;
    txt1.Text = "The TextWrap property is currently set to NoWrap.";
}
public void WrapWithOverflow(object sender, RoutedEventArgs e)
{
    txt2.TextWrapping = System.Windows.TextWrapping.WrapWithOverflow;
    txt1.Text = "The TextWrap property is currently set to WrapWithOverflow.";
}
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

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

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

See Also

Reference

TextWrapping
TextWrapping