Understanding WPF Controls: TextBlock, TextBox, RichTextBox, and More
TextBlock Control
The TextBlock control serves as a specialized element for rendering text within WPF appplications. It offers enhanced functionality compared to Label controls, including advanced formatting options and improved performence.
Key features of TextBlock:
- Text Formatting: Supports font styles, sizes, bold, italic, and other visual attributes.
- Line Wrapping: Automatically wraps long text without truncation.
- Inline Elements: Allows embedding hyperlinks, icons, and other inline content.
- Rich Text Support: Displays formatted text with varying fonts, colors, and decorations.
- Performance Optimization: Efficient handling of large text volumes.
Core properties include:
FontWeight: Controls text thickness (Normal, Bold).FontStyle: Applies italic or normal styling.FontFamily: Specifies the typeface (e.g., Arial, Microsoft YaHei UI).Text: Sets or retrieves displayed text.TextWrapping: Determines line breaking behavior (NoWrap, Wrap).Foreground: Sets the text color.Background: Defines background color.Padding: Adds space between content and border.TextAlignment: Aligns text horizontally (Left, Right, Center).TextTrimming: Handles overflow with ellipsis or clipping.Inlines: Collection for Run elements with individual styling capabilities.
Example XAML:
<WrapPanel Margin="10">
<TextBlock Text="Basic TextBlock" Margin="5"/>
<TextBlock FontWeight="Bold" Text="Bold Text" Margin="5"/>
<TextBlock FontStyle="Italic" Text="Italic Text" Margin="5"/>
<TextBlock FontFamily="Microsoft YaHei UI" Text="YaHei Font" Margin="5"/>
<TextBlock FontSize="30" Text="Large Text" Margin="5"/>
<TextBlock Foreground="Red" Text="Red Text" Margin="5"/>
<TextBlock Foreground="Yellow" Background="Red" Text="Colored Background" Margin="5"/>
<TextBlock Foreground="Yellow" Background="Red" Text="Padded Text" Padding="10" Margin="5"/>
<TextBlock Background="LightGray" Height="25" Margin="5">
<Run Foreground="Red">First part</Run>
<Run Foreground="Green">Second part</Run>
<Run Foreground="Blue">Third part</Run>
</TextBlock>
<Grid Width="150" Height="100" Background="LightGoldenrodYellow" Margin="5">
<TextBlock TextWrapping="Wrap" Margin="10" Text="This demonstrates TextWrapping property"/>
</Grid>
</WrapPanel>
TextBox Control
The TextBox control facilitates user input of textual data. It inherits from TextBoxBase which itself extends Control.
TextBoxBase Properties
VerticalScrollBarVisibility: Controls vertical scrollbar visibility.HorizontalScrollBarVisibility: Manages horizontal scrollbar visibility.AcceptsReturn: Enables newline insertion via Enter key.AcceptsTab: Controls tab character insertion.IsReadOnlyCaretVisible: Shows caret in read-only mode.SelectionOpacity: Sets selection transparency.IsUndoEnabled: Enables undo functionality.UndoLimit: Limits number of undo operations.AutoWordSelection: Auto-selects words.SelectionBrush: Paints selected text area.IsReadOnly: Locks editing capability.CaretBrush: Configures cursor appearance.IsInactiveSelectionHighlightEnabled: Highlights selections when inactive.
Events:
TextChanged: Triggers upon content modification.SelectionChanged: Fires when selection range changes.
TextBox Specific Properties
MinLines: Minimum visible rows.MaxLines: Maximum visible rows.CharacterCasing: Controls character case (Normal, Lower, Upper).MaxLength: Limits manual input length.TextAlignment: Aligns text (Left, Right, Center).CaretIndex: Current cursor position.SelectionLength: Number of selected characters.SelectionStart: Starting index of selection.Typography: Applies typographic variations.LineCount: Total lines in textbox.TextDecorations: Applies text effects like underline.SelectedText: Retrieves selected content.TextWrapping: Controls word wrapping.
Example XAML:
<Grid Margin="20">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBox x:Name="inputBox" Grid.Row="0" Margin="5" Width="200" TextAlignment="Center" Text="Enter Name"
GotFocus="OnGotFocus" LostFocus="OnLostFocus"/>
<TextBox x:Name="readOnlyBox" Grid.Row="1" Margin="5" Width="200" Text="Read Only Box" IsReadOnly="True"/>
<TextBox x:Name="multiLineBox" Grid.Row="2" Margin="5" Width="200" Height="80" TextWrapping="Wrap"
Text="Multi-line text box example" GotFocus="OnGotFocus" LostFocus="OnLostFocus"/>
<TextBox x:Name="limitBox" Grid.Row="3" Margin="5" Width="200" MaxLength="10" Text="Max 10 chars"
GotFocus="OnGotFocus" LostFocus="OnLostFocus"/>
</Grid>
Code-behind:
private void OnGotFocus(object sender, RoutedEventArgs e)
{
var textBox = sender as TextBox;
if (textBox != null) textBox.Text = string.Empty;
}
private void OnLostFocus(object sender, RoutedEventArgs e)
{
var textBox = sender as TextBox;
if (textBox == null) return;
switch (textBox.Name)
{
case "inputBox":
textBox.Text = "Enter Name";
break;
case "multiLineBox":
textBox.Text = "Multi-line text box example";
break;
case "limitBox":
textBox.Text = "Max 10 chars";
break;
}
}
RichTextBox Control
RichTextBox enables complex document creation with formatting, images, and links. It supports FlowDocument for rich content management.
Constructors:
public RichTextBox(): Default constructor.public RichTextBox(FlowDocument document): Initializes with document.
Properties:
Document: Gets or sets the underlying FlowDocument.IsDocumentEnabled: Enables/disables document mode.Selection: Current text selection object.CaretPosition: Cursor location within document.
Methods:
GetNextSpellingErrorPosition: Finds next spelling error.GetPositionFromPoint: Locates text position from coordinates.GetSpellingError: Retrieves spelling error at position.GetSpellingErrorRange: Gets range containing spelling error.ShouldSerializeDocument: Indicates if document should be serialized.
Example XAML:
<RichTextBox x:Name="richTextBox" Margin="10">
<FlowDocument>
<Paragraph>
<Run FontWeight="Bold">RichTextBox Sample</Run>
</Paragraph>
<Paragraph>
<Run>Advanced text editing capabilities.</Run>
</Paragraph>
<Paragraph>
<Run>You can apply different fonts, styles, and colors here.</Run>
</Paragraph>
</FlowDocument>
</RichTextBox>
ToolTip Control
ToolTip displays contextual help messages attached to other controls. It requires a parent control and appears on hover.
Properties:
IsOpen: Controls visibility state.StaysOpen: Prevents automatic closure.Placement: Position relative to target.HorizontalOffset,VerticalOffset: Adjust positioning.HasDropShadow: Adds shadow effect.
Events:
Opened: Triggered when shown.Closed: Triggered when hidden.
Example XAML:
<Button Content="Hover Me" HorizontalAlignment="Center" VerticalAlignment="Center">
<Button.ToolTip>
<ToolTip Content="This is a ToolTip."/>
</Button.ToolTip>
</Button>
Popup Control
Popup creates floating windows that can contain any UI elements. Unlike ToolTip, it supports complex layouts.
Properties:
IsOpen: Toggles visibility.PlacementTarget: Target element for positioning.Placement: Alignment options.HorizontalOffset,VerticalOffset: Offset values.StaysOpen: Keeps popup open after focus loss.Child: Single child element.PopupAnimation: Animation effect on open/close.
Events:
Opened: Raised when popup opens.Closed: Raised when popup closes.
Example XAML:
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
<CheckBox x:Name="menuToggle" Content="Show Menu" Height="30" Margin="5" ToolTip="Toggle menu" Checked="OnMenuToggle"/>
<Popup Name="contextMenu" IsOpen="{Binding IsChecked, ElementName=menuToggle}"
PlacementTarget="{Binding ElementName=menuToggle}" StaysOpen="True">
<Border BorderThickness="1" Background="LightBlue">
<StackPanel>
<Button Content="Option 1" Click="OnMenuItemClick"/>
<Button Content="Option 2" Click="OnMenuItemClick"/>
<Button Content="Option 3" Click="OnMenuItemClick"/>
</StackPanel>
</Border>
</Popup>
</StackPanel>
Code-behind:
private void OnMenuItemClick(object sender, RoutedEventArgs e)
{
var button = sender as Button;
if (button == null) return;
switch (button.Content.ToString())
{
case "Option 1":
MessageBox.Show("Option 1 selected");
contextMenu.IsOpen = false;
break;
case "Option 2":
MessageBox.Show("Option 2 selected");
contextMenu.IsOpen = false;
break;
case "Option 3":
MessageBox.Show("Option 3 selected");
contextMenu.IsOpen = false;
break;
}
}
private void OnMenuToggle(object sender, RoutedEventArgs e)
{
var checkBox = sender as CheckBox;
contextMenu.IsOpen = checkBox?.IsChecked == true;
}
Image Control
The Image control renders various image formats (BMP, GIF, JPG, PNG, TIFF, etc.). For animated GIFs, third-party libraries like WpfAnimatedGif are required.
Properties:
Stretch: Scaling behavior (None, Fill, Uniform, UniformToFill).StretchDirection: Scaling constraints (UpOnly, DownOnly, Both).Source: Image source.BaseUri: Base URI for image resources.
Events:
DpiChanged: Triggers when display DPI changes.ImageFailed: Occurs on loading failure.
Example XAML:
<Image Width="200" Height="150" Stretch="Uniform" Source="/Images/meimei.png" />
Ensure image build action is set to 'Copy Always' or 'Copy If Newer'.