π Lecture 17 β WPF Layout, Sizing, Positioning, and Attached Properties
π Overview: This lecture completes the discussion of XAML and attached properties, then moves into WPF layout fundamentals. It explains how elements collaborate with parent panels to determine size and position, and covers the properties that control sizing, alignment, margins, padding, visibility, and transforms. Understanding these concepts is essential for designing responsive WPF user interfaces.
ποΈ Topics Covered
The lecture begins by revisiting a XAML window example and explaining how attached properties work internally through dependency properties and the registerattached method. It then transitions into layout, explaining the parent-child collaboration model, size-related properties (Height, Width, Min/Max, Actual sizes), Margin and Padding with their Thickness type, Visibility values, Horizontal/Vertical Alignment, Content Alignment, FlowDirection for right-to-left languages, and finally LayoutTransform vs RenderTransform.
π Lecture Summary
Attached Properties and Code-Behind
Attached properties allow setting properties on an element from an unrelated class. The XAML parser converts shorthand attribute values (like "Italic") into enumeration values (FontStyles.Italic) using TypeConverters. In C#, a call like TextElement.SetFontSize(panel, 30) internally calls panel.SetValue(TextElement.FontSizeProperty, 30). The property wrapper is just a convenience; it always calls DependencyObject.SetValue and GetValue.
π Definition β Attached Property: A dependency property that is defined by one class but can be set on any other DependencyObject. Used to extend the functionality of existing elements without modifying them.
π Example: Setting a Buttonβs unrelated attached property from code:
okButton.SetValue(ItemsControl.IsTextSearchEnabledProperty, true);
This works because SetValue can set any dependency property on any DependencyObject.
π‘ Why this matters: Attached properties allow panels (like StackPanel, Grid) to attach layout information (e.g., Grid.Row, Canvas.Top) to their children without bloating the child classes with layout-specific properties.
Registering Attached Properties
TextElement.FontSizeProperty is registered using DependencyProperty.RegisterAttached. This method is optimized for attached properties. The Control class then reuses the same property with AddOwner:
Control.FontSizeProperty = TextElement.FontSizeProperty.AddOwner(typeof(Control), ...);
This allows Control subclasses to inherit the same underlying property ID while potentially having different metadata.
π Formula β RegisterAttached: DependencyProperty.RegisterAttached("name", typeof(propertyType), typeof(ownerType), metadata, validateValueCallback) β Creates a new attached dependency property.
π Formula β AddOwner: existingProperty.AddOwner(typeof(newOwnerType), metadata) β Shares an existing property with a new class.
π Example: TextElement.FontSizeProperty is the canonical owner; Control.FontSizeProperty is the same underlying field, registered via AddOwner.
The Tag Property
All FrameworkElements have a Tag property of type object for storing arbitrary custom data. It is a great mechanism for extending "sealed" classes. While you can use SetValue with any property, Tag is the recommended, cleaner approach.
π Example:
GeometryModel3D model = new GeometryModel3D();
model.SetValue(FrameworkElement.TagProperty, "my custom data");
Layout Fundamentals
Layout in WPF boils down to parent-child relationships. Parents and children collaborate:
- Parent tells child how much space is available.
- Child asks for how much it really needs.
- Parent then positions the child.
All layout elements derive from System.Windows.UIElement. Panels (parents that support multiple children) derive from the abstract System.Windows.Controls.Panel.
Size Properties
FrameworkElement provides several size properties. Explicit Height and Width take precedence when within Min/Max range. Avoid explicit sizing when possible; defaults are Min=0, Max=Infinity. Double.NaN (or "Auto" in XAML) means "size to content".
π Definition β ActualHeight/ActualWidth: Read-only properties that report the final rendered size after layout completes. π Definition β DesiredSize: The size the child requested during the measure pass of layout. π Definition β RenderSize: The final size assigned by the parent during the arrange pass.
Margin and Padding
All FrameworkElements have Margin (extra space outside the element's edges). Control (and Border) also have Padding (space inside the edges). Both are of type Thickness, which can represent 1, 2, or 4 values. Negative margins are allowed.
π Formula β Thickness values in XAML:
Margin="10"β All sides = 10Margin="20,5"β Left/Right=20, Top/Bottom=5Margin="0,10,20,30"β Left=0, Top=10, Right=20, Bottom=30
π Example (C# equivalent):
myLabel.Margin = new Thickness(10);
myLabel.Margin = new Thickness(20, 5, 20, 5);
myLabel.Margin = new Thickness(0, 10, 20, 30);
The LengthConverter TypeConverter supports explicit units: cm, pt, in, px (default). All measurements are in device-independent pixels (DIPs), 1/96 inch, regardless of screen DPI.
Visibility
UIElement.Visibility can have three Visibility enum values:
π Definition β Visible: Element is rendered and participates in layout (normal). π Definition β Collapsed: Element is invisible and does not participate in layout (takes no space). π Definition β Hidden: Element is invisible but still participates in layout (takes space but not drawn).
π Example (XAML):
<!-- Collapsed button takes no space, second button shifts up -->
<StackPanel Height="100" Background="Aqua">
<Button Visibility="Collapsed">Collapsed Button</Button>
<Button>Below a Collapsed Button</Button>
</StackPanel>
<!-- Hidden button still takes space, second button stays in place -->
<StackPanel Height="100" Background="Aqua">
<Button Visibility="Hidden">Hidden Button</Button>
<Button>Below a Hidden Button</Button>
</StackPanel>
Position and Alignment
Instead of explicit (x,y) coordinates, WPF uses alignment controlled by the parent. HorizontalAlignment values: Left, Center, Right, Stretch. VerticalAlignment values: Top, Center, Bottom, Stretch. Stretch is the default and makes the element fill the available space. Alignment is only useful when the parent gives more space than the child needs.
π Example (XAML):
<StackPanel>
<Button HorizontalAlignment="Left" Background="Red">Left</Button>
<Button HorizontalAlignment="Center" Background="Orange">Center</Button>
<Button HorizontalAlignment="Right" Background="Yellow">Right</Button>
<Button HorizontalAlignment="Stretch" Background="Lime">Stretch</Button>
</StackPanel>
Content Alignment
Controls also have HorizontalContentAlignment and VerticalContentAlignment. These determine how the control's content fills the space inside the control (similar relationship to Margin vs Padding). Defaults are Left and Top; Buttons override defaults. TextBlock does not stretch like a Control.
π Example (XAML):
<StackPanel>
<Button HorizontalContentAlignment="Left" Background="Red">Left</Button>
<Button HorizontalContentAlignment="Center" Background="Orange">Center</Button>
<Button HorizontalContentAlignment="Right" Background="Yellow">Right</Button>
<Button HorizontalContentAlignment="Stretch" Background="Lime">Stretch</Button>
</StackPanel>
FlowDirection
FrameworkElement.FlowDirection can reverse the visual flow. Used for right-to-left languages (e.g., Arabic, Hebrew).
π Example (XAML):
<StackPanel>
<Button FlowDirection="LeftToRight" HorizontalContentAlignment="Left" ... />
<Button FlowDirection="RightToLeft" HorizontalContentAlignment="Left" ... />
</StackPanel>
Transforms
All FrameworkElements have two Transform properties derived from System.Windows.Media.Transform:
- LayoutTransform: Applied before layout β affects the element's size and how siblings are arranged.
- RenderTransform: Applied after layout β only affects the visual appearance; siblings are not rearranged.
UIElement also has RenderTransformOrigin to specify the pivot point for the transform.
π‘ Why this matters: Use LayoutTransform for permanent size changes (like rotating a button that should affect its neighbors); use RenderTransform for animations or visual effects that shouldn't disturb the layout.
β Key Takeaways
- Attached properties are dependency properties registered with
RegisterAttached, allowing any element to host properties defined by unrelated classes (e.g., panels attaching layout info to children). Always prefer theTagproperty for storing custom data rather than abusing unrelated properties. - Layout is a collaborative, two-phase process: parents ask children their desired size (Measure pass), then assign them their final size and position (Arrange pass). Avoid explicit
Height/Widthwhen possible; preferMin/MaxandAuto(NaN). - Margin is space outside the element; Padding is space inside. Both use the
Thicknesstype. Visibility has three distinct states:Visible,Hidden(invisible but takes space), andCollapsed(invisible and takes no space β like removing the element). - Alignment (
HorizontalAlignment/VerticalAlignment) and ContentAlignment (HorizontalContentAlignment/VerticalContentAlignment) control placement within available space and the element's inner space respectively.Stretchis the default and makes the element fill available space. - Transforms come in two flavors:
LayoutTransformaffects layout (reflows siblings), whileRenderTransformonly affects visuals. UseRenderTransformOriginto control the pivot point.
π§ Quick Revision Questions
- What is the difference between
MarginandPaddingin WPF, and which type do they use? - What is the difference between
Visibility.HiddenandVisibility.Collapsed? - How is an attached property registered, and why are they useful for panels?
- When should you use
LayoutTransforminstead ofRenderTransform? - What does
HorizontalAlignment="Stretch"do, and which is the default alignment?
π Lecture 18 β Layout and Transformations in WPF
π Overview: This lecture explores layout transformations and panels in WPF. It explains how to apply built-in transforms (rotate, scale, skew, translate, matrix) to UI elements, both as layout and render transforms, and introduces the five main built-in panels (Canvas, StackPanel, WrapPanel, DockPanel, and Grid) for arranging elements. Understanding these concepts is crucial for creating flexible, responsive user interfaces.
ποΈ Topics Covered
The lecture begins by revising size and position properties, then distinguishes between layout transform and render transform. It covers all five built-in transforms: RotateTransform, ScaleTransform, SkewTransform, TranslateTransform, and MatrixTransform, along with their properties and usage. It also explains how to combine transforms using TransformGroup. The second half introduces the five main built-in panels in System.Windows.Controls: Canvas, StackPanel, WrapPanel, DockPanel, and Grid, with detailed examples for Canvas and StackPanel, plus an introduction to VirtualizingStackPanel and WrapPanel.
π Lecture Summary
Size and Position Properties Revision
The lecture begins with a refresher on size and position properties. Layout transform is applied before rendering and affects the element's layout position. Render transform is applied after rendering and does not affect layout. The PointConverter is used to specify the origin for transformations.
Built-in Transforms
The five built-in transforms are: RotateTransform, ScaleTransform, SkewTransform, TranslateTransform, and MatrixTransform. Each transform can be applied as a render transform or layout transform, with specific effects.
π Definition β RenderTransformOrigin: A property (e.g., RenderTransformOrigin="0.5,0.5") that specifies the point around which a render transform is applied, relative to the element's size.
π Formula: RenderTransformOrigin="x,y" β The origin point expressed as fractions (0 to 1) of the element's width and height.
π Example: The button below rotates 45 degrees around its center:
<Button RenderTransformOrigin="0.5,0.5" Background="Orange">
<Button.RenderTransform>
<RotateTransform Angle="45"/>
</Button.RenderTransform>
Rotated 45
</Button>
π Definition β RotateTransform: Rotates an element by a specified Angle (in degrees), with optional CenterX and CenterY properties (default 0). Center is useless for layout transform but useful when grouping render transforms.
π Example: Applying rotate transform only to the inner TextBlock:
<Button Background="Orange">
<TextBlock RenderTransformOrigin="0.5,0.5">
<TextBlock.RenderTransform>
<RotateTransform Angle="45"/>
</TextBlock.RenderTransform>
45
</TextBlock>
</Button>
π Definition β ScaleTransform: Scales an element by ScaleX (horizontal) and ScaleY (vertical) factors, with optional CenterX and CenterY origins.
π Example: Different scaling modes applied to buttons in a StackPanel:
<StackPanel Width="100">
<Button Background="Red">No Scaling</Button>
<Button Background="Orange">
<Button.RenderTransform>
<ScaleTransform ScaleX="2"/>
</Button.RenderTransform>
X
</Button>
<Button Background="Yellow">
<Button.RenderTransform>
<ScaleTransform ScaleX="2" ScaleY="2"/>
</Button.RenderTransform>
X + Y
</Button>
<Button Background="Lime">
<Button.RenderTransform>
<ScaleTransform ScaleY="2"/>
</Button.RenderTransform>
Y
</Button>
</StackPanel>
π‘ Why this matters: Stretch and ScaleTransform only affect the element if more than stretch is applied. Padding is scaled but margin is not. ScaleTransform does not affect ActualHeight, ActualWidth, or RenderSize.
π Definition β SkewTransform: Skews an element horizontally (AngleX) and/or vertically (AngleY), with optional CenterX and CenterY origins (all default 0).
π Properties: AngleX β Amount of horizontal skew; AngleY β Amount of vertical skew; CenterX β Origin for horizontal skew; CenterY β Origin for vertical skew.
π Definition β TranslateTransform: Moves an element by X (horizontal) and Y (vertical) amounts. It has no effect as a layout transform, only as a render transform.
π Properties: X β Amount to move horizontally (default 0); Y β Amount to move vertically (default 0).
π Definition β MatrixTransform: Uses a single Matrix property (of type System.Windows.Media.Matrix) representing a 3x3 affine transformation matrix. This is the only transform with a type converter to convert a string.
π Example: Using MatrixTransform with string shorthand:
<Button RenderTransform="1,0,0,1,10,20"/>
The string "1,0,0,1,10,20" represents a matrix with translation by 10 (X) and 20 (Y).
Combining Transforms
Transforms can be combined by applying both layout and render transforms, or by using a TransformGroup (a Transform-derived class) that calculates the combined matrix automatically.
π Example: Combining rotate, scale, and skew transforms in a TransformGroup:
<Button>
<Button.RenderTransform>
<TransformGroup>
<RotateTransform Angle="45"/>
<ScaleTransform ScaleX="5" ScaleY="1"/>
<SkewTransform AngleX="30"/>
</TransformGroup>
</Button.RenderTransform>
OK
</Button>
β οΈ Important: Not all elements can be transformed.
Panels for Layout
Layout of individual elements is finally decided by the parent panel. There are five main built-in panels in System.Windows.Controls:
- Canvas
- StackPanel
- WrapPanel
- DockPanel
- Grid
Content overflow occurs when parents and children cannot agree on the use of available space.
π Definition β Canvas: The most basic panel, rarely used. It uses explicit coordinates (device-independent pixels) relative to any corner of the window. Elements are positioned using attached properties: Left, Top, Right, and Bottom. Default offsets are from top-left.
π Example: Positioning buttons in a Canvas using attached properties:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="Buttons in a Canvas">
<Canvas>
<Button Background="Red">Left=0, Top=0</Button>
<Button Canvas.Left="18" Canvas.Top="18" Background="Orange">Left=18, Top=18</Button>
<Button Canvas.Right="18" Canvas.Bottom="18" Background="Yellow">Right=18, Bottom=18</Button>
<Button Canvas.Right="0" Canvas.Bottom="0" Background="Lime">Right=0, Bottom=0</Button>
<Button Canvas.Right="0" Canvas.Top="0" Background="Aqua">Right=0, Top=0</Button>
<Button Canvas.Left="0" Canvas.Bottom="0" Background="Magenta">Left=0, Bottom=0</Button>
</Canvas>
</Window>
π‘ Why this matters: If Left and Right are both set, Right is ignored. If Top and Bottom are both set, Bottom is ignored. Z-order (controlled by Canvas.ZIndex) determines which element appears on top when elements overlap.
π Example: Z-order with Canvas.ZIndex:
<Canvas>
<Button Canvas.ZIndex="1" Background="Red">On Top!</Button>
<Button Background="Orange">On Bottom with a Default ZIndex=0</Button>
</Canvas>
π Definition β StackPanel: A popular, simple, and useful panel that stacks elements sequentially. It has no attached properties. Orientation can be Horizontal or Vertical (default is Vertical). Default horizontal direction is based on FlowDirection.
π Definition β VirtualizingStackPanel: A virtualizing panel that saves space for offscreen content when data binding (e.g., a ListBox uses it).
π Definition β WrapPanel: Wraps elements to additional rows or columns when there is not enough space. It has no attached properties. Orientation is Horizontal by default. ItemHeight and ItemWidth provide uniform size for all children and are not set by default.
β Key Takeaways
The most critical concepts from this lecture are the distinction between layout transforms (applied before rendering, affecting layout) and render transforms (applied after, not affecting layout), and the properties of all five built-in transforms: RotateTransform (Angle, CenterX, CenterY), ScaleTransform (ScaleX, ScaleY, CenterX, CenterY), SkewTransform (AngleX, AngleY, CenterX, CenterY), TranslateTransform (X, Y β useless as layout transform), and MatrixTransform (the only one with a type converter). You must remember how to combine transforms using TransformGroup and that padding is scaled but margin is not during scaling. For panels, know that Canvas uses explicit coordinates with attached properties (Left, Top, Right, Bottom) and Z-order via Canvas.ZIndex, StackPanel stacks elements with configurable orientation, and WrapPanel wraps content into additional rows or columns. Finally, be aware that content overflow occurs when parent and child disagree on space usage, and that not every element supports transformations.
π§ Quick Revision Questions
- What is the difference between LayoutTransform and RenderTransform?
- Which transform has a type converter allowing a string shorthand like
"1,0,0,1,10,20"? - In a Canvas, if both
Canvas.LeftandCanvas.Rightare set for a button, which property takes precedence? - How can you combine multiple transforms (e.g., rotate, scale, and skew) into a single render transform?
- What are the five main built-in panels in
System.Windows.Controls?
π Lecture 19 β Dock Panel and Grid
π Overview: This lecture introduces two essential WPF layout panels: the DockPanel for docking elements to sides, and the Grid for multi-row/column arrangements. Understanding these panels is crucial for building flexible and responsive user interfaces, as they control how child elements are positioned and resized within a window.
ποΈ Topics Covered
The lecture covers the DockPanel panel, its attached Dock property with Top/Left/Right/Bottom values, the LastChildFill property, and the effect of alignment on docked elements. It then introduces the Grid panel as the most versatile layout container, explaining row and column definitions, attached properties (Grid.Row, Grid.Column), spanning (RowSpan, ColumnSpan), sizing modes (Absolute, Auto, Star), and the GridSplitter for interactive resizing.
π Lecture Summary
DockPanel
The DockPanel allows easy docking of elements to an entire side of the panel. It uses the Dock attached property which can be set to Left, Right, Top, or Bottom. The last child in the DockPanel fills the remaining space by default, but this behavior can be disabled by setting LastChildFill="False". The order in which elements are added to the DockPanel matters because it affects which corners are occupied by which elements.
ποΈ Code Example (Basic DockPanel):
<DockPanel>
<Button DockPanel.Dock="Top" Background="Red">1 (Top)</Button>
<Button DockPanel.Dock="Left" Background="Orange">2 (Left)</Button>
<Button DockPanel.Dock="Right" Background="Yellow">3 (Right)</Button>
<Button DockPanel.Dock="Bottom" Background="Lime">4 (Bottom)</Button>
<Button Background="Aqua">5</Button>
</DockPanel>
π‘ Why this matters: By default, elements in a DockPanel stretch to fill the entire side. Understanding how alignment works is essential to control exact positioning.
ποΈ Code Example (DockPanel with Alignment):
<DockPanel>
<Button DockPanel.Dock="Top" HorizontalAlignment="Right" Background="Red">1 (Top, Align=Right)</Button>
<Button DockPanel.Dock="Left" VerticalAlignment="Bottom" Background="Orange">2 (Left, Align=Bottom)</Button>
<Button DockPanel.Dock="Right" VerticalAlignment="Bottom" Background="Yellow">3 (Right, Align=Bottom)</Button>
<Button DockPanel.Dock="Bottom" HorizontalAlignment="Right" Background="Lime">4 (Bottom, Align=Right)</Button>
<Button Background="Aqua">5</Button>
</DockPanel>
π Definition β DockPanel: A layout panel that docks child elements to one of its four sides (Top, Left, Right, Bottom), with the last child filling the remaining space by default.
π Property: DockPanel.Dock attached property β Sets which side of the panel the element should dock to.
π Example: Docking a button to the top: <Button DockPanel.Dock="Top">Button Text</Button>
Grid
The Grid is the most versatile layout panel in WPF. It is the default panel in Visual Studio and Expression Blend. It allows arranging elements in multiple rows and columns, similar to an HTML table. Note that there is also a Table class, but it is a FrameworkContentElement, not a UIElement, so it behaves differently.
Elements in a Grid are positioned using the Grid.Row and Grid.Column attached properties, which are zero-based (default is 0,0). Multiple elements can occupy the same cell, in which case they overlap based on z-order (last added is on top). Cells can also be empty.
ποΈ Code Example (Grid with Four Rows and Two Columns):
<Grid Background="lightblue">
<!-- Define four rows: -->
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<!-- Define two columns: -->
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<!-- Arrange the children: -->
<Label Grid.Row="0" Grid.Column="0" Background="Blue" Foreground="White">Start Page</Label>
<GroupBox Grid.Row="1" Grid.Column="0" Background="White" Header="Recent Projects"/>
<GroupBox Grid.Row="2" Grid.Column="0" Background="White" Header="Getting Started"/>
<GroupBox Grid.Row="3" Grid.Column="0" Background="White" Header="Headlines"/>
<GroupBox Grid.Row="1" Grid.Column="1" Background="White" Header="Online Articles">
<ListBox>
<ListBoxItem>Article #1</ListBoxItem>
<ListBoxItem>Article #2</ListBoxItem>
<ListBoxItem>Article #3</ListBoxItem>
<ListBoxItem>Article #4</ListBoxItem>
</ListBox>
</GroupBox>
</Grid>
π Definition β Grid: A layout panel that arranges child elements in a matrix of rows and columns, defined by RowDefinitions and ColumnDefinitions.
π Properties: Grid.Row (default 0), Grid.Column (default 0), Grid.RowSpan (default 1), Grid.ColumnSpan (default 1) β Used to position and span elements across cells.
π Example: Placing a button in row 2, column 1: <Button Grid.Row="2" Grid.Column="1">Click Me</Button>
Grid Sizing Modes
Grid rows and columns can be sized using three modes:
- Absolute sizing: Fixed size in device-independent pixels (e.g.,
Width="100"). Does not grow or shrink. - Auto sizing: Size to fit content (e.g.,
Width="Auto"). - Proportional or Star sizing: Grows or shrinks to fill remaining space (e.g.,
Width="*"orWidth="2*").
When using star sizing, * takes all remaining space. If multiple rows/columns use *, they divide the remaining space proportionally. For example, 2* is twice as wide as * (which equals 1*). The remaining space is calculated after absolute and auto-sized rows/columns are accounted for. Default width and height for Grid rows/columns are *.
ποΈ GridLength in Procedural Code:
GridLength length = new GridLength(100); // Absolute pixel value
GridLength length = new GridLength(0, GridUnitType.Auto); // Auto size
GridLength length = new GridLength(100, GridUnitType.Pixel); // Absolute pixel
GridLength length = new GridLength(2, GridUnitType.Star); // 2* proportional
π Definition β GridLength: A structure used to specify the size of a Grid row or column, supporting Absolute (pixel), Auto, or Star (proportional) sizing.
π Formula: Width="2*" β Takes twice the space of Width="*" (1*) from the remaining available space.
π Example: In a Grid with two columns: ColumnDefinition Width="*" and ColumnDefinition Width="2*" β The second column is twice as wide as the first, dividing the remaining space in a 1:2 ratio.
GridSplitter
The GridSplitter is used for interactive resizing of Grid rows and columns by the user. Any number of GridSplitters can be added to a Grid. It can be used to resize an entire row or column. At least one cell resizes, and the behavior of other cells depends on whether they use absolute or proportional sizing.
The GridSplitter fits in one cell, but its behavior affects the entire row or column, so it is better to use span to cover the entire row/column. Which cells are affected depends on the GridSplitter's alignment values. Default HorizontalAlignment is Right, and default VerticalAlignment is Stretch. Reasonable use requires stretching in one dimension.
When all cells are proportionally sized, changes to the splitter modify the coefficients accordingly. When cells have absolute sizing, only the top or left of the cells changes, and remaining cells are pushed down or right.
The GridSplitter has a ResizeDirection property (default Auto, or can be set to Rows or Columns) and a ResizeBehavior property for explicit control. ResizeDirection takes effect only when stretching in both directions. ResizeBehavior defaults to BasedOnAlignment and can be set to PreviousAndCurrent, CurrentAndNext, or PreviousAndNext to control which two rows/columns are directly affected by resizing. The best practice is to place the GridSplitter in its own auto-sized row or column so it does not overlap existing content.
π Definition β GridSplitter: A control that allows users to interactively resize Grid rows and columns at runtime.
π Properties: ResizeDirection (Auto, Rows, Columns), ResizeBehavior (BasedOnAlignment, PreviousAndCurrent, CurrentAndNext, PreviousAndNext).
π Example: Add a GridSplitter between two columns: Place a <GridSplitter/> in its own auto-sized column between the two columns to allow resizing.
β Key Takeaways
The DockPanel is ideal for docking toolbars, menus, or status bars to the edges of a window, with the last child filling the remaining spaceβa pattern often used in top-level interface layouts. The Grid is the most powerful and default layout panel in WPF, supporting multi-row/column arrangements with three sizing modes: Absolute (fixed pixels), Auto (size to content), and Star/Proportional (dynamic resizing relative to available space). Understanding how to use attached properties like Grid.Row, Grid.Column, Grid.RowSpan, and Grid.ColumnSpan is essential for placing and spanning elements. The GridSplitter provides interactive resizing, and its behavior depends on cell sizing modes and alignment; best practice is to place it in its own auto-sized row or column. Finally, the Grid is a superset of the StackPanel in functionality, and the order of elements matters both in DockPanel (for corner allocation) and Grid (for z-order overlap).
π§ Quick Revision Questions
- What are the four possible values for the
DockPanel.Dockattached property, and what happens to the last child by default? - How do you define rows and columns in a Grid using XAML? What are the attached properties used for positioning?
- What are the three sizing modes for Grid rows and columns? Explain how star sizing distributes space when multiple rows/columns use it.
- How does a GridSplitter affect cells with absolute sizing versus proportional (star) sizing?
- What is the purpose of the
ResizeBehaviorproperty on a GridSplitter, and what are its possible values?
π Lecture 20 β Letβs revise grid.
π Overview: This lecture covers advanced grid layout features in WPF, focusing on the
SharedSizeGroupproperty which allows multiple rows or columns to maintain equal sizing when resized viaGridSplitter. It also addresses content overflow handling strategies including clipping, scrolling, scaling, wrapping, and trimming, and introduces theScrollViewerandViewboxcontrols for managing content that exceeds available space.
ποΈ Topics Covered
The lecture begins by revising Grid layout with GridSplitter, then introduces SharedSizeGroup and IsSharedSizeScope for synchronized column/row sizing across grids. It then covers five methods for handling content overflow: clipping, scrolling, scaling, wrapping, and trimming. Specific controls discussed include the ScrollViewer for adding scroll bars and the Viewbox for scaling content to fill available space, with properties like Stretch and StretchDirection. The lecture concludes with a practical example of creating a Visual Studio-like interface.
π Lecture Summary
[Letβs revise grid.]
The lecture starts with a basic Grid example demonstrating ColumnDefinitions with Width="Auto" and using GridSplitter to allow interactive column resizing. This establishes the foundation for more advanced grid features.
π Definition β GridSplitter: A control that allows users to resize columns or rows of a Grid at runtime by dragging the splitter bar.
[SharedSizeGroup enables multiple rows/cols to remain the same width/height when length changed via GridSplitter.]
The SharedSizeGroup property is introduced to solve the problem of maintaining equal column widths across different grid cells when one column is resized. IsSharedSizeScope is a boolean attached property of Grid that enables SharedSizeGroup to work across multiple grids, meaning size groups can be shared under a common parent with IsSharedSizeScope="True". Without this, the shared size groups would not be recognized across separate grid instances.
π Definition β SharedSizeGroup: A property that links multiple columns or rows together so they maintain the same width or height, even when resized using a GridSplitter.
π Formula: <Grid IsSharedSizeScope="True"> β enables SharedSizeGroup to work across multiple grids under this parent.
π Example:
<Grid IsSharedSizeScope="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="mygroup"/>
<ColumnDefinition/>
<ColumnDefinition SharedSizeGroup="mygroup"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Background="Red" ... />
<GridSplitter Grid.Column="0" Width="5"/>
<Label Grid.Column="1" Background="Orange" ... />
<Label Grid.Column="2" Background="Yellow" ... />
</Grid>
Here, columns 0 and 2 share the same size group "mygroup". When the GridSplitter at column 0 resizes column 0, column 2 automatically adjusts to maintain the same width. The IsSharedSizeScope="True" is on the outer Grid.
π‘ Why this matters: This enables creating consistent, proportional layouts where resizing one section automatically adjusts related sections, essential for tools like IDEs or dashboards.
[Content overflow can be dealt with Clipping, Scrolling, Scaling, Wrapping and Trimming.]
This section details five strategies for handling content that exceeds the available space of a container. Wrapping is already seen with text, but for non-text elements, only WrapPanel enables wrapping behavior. Trimming is an intelligent form of clipping specifically for text in TextBlock and AccessText, where the TextTrimming property can be set to None (default), CharacterEllipsis, or WordEllipsis. Clipping is the default behavior for most panels, where content beyond edges is simply cut off. The ClipToBounds property on all UIElement controls determines whether they can draw outside their bounds, but no control can draw outside the window or page. Canvas and UniformGrid do not clip unless ClipToBounds is set to True. Button has this property set to False by default. Placing a Canvas inside a Grid cell can avert clipping. Crucially, clipping occurs before RenderTransform, so you cannot shrink content back into view after it has been clipped.
π Definition β TextTrimming: A property (CharacterEllipsis or WordEllipsis) that replaces clipped text with an ellipsis (β...β) at the character or word boundary.
π Definition β ClipToBounds: A UIElement property that, when True, prevents the element from drawing content beyond its own boundaries.
π Property: TextTrimming="CharacterEllipsis" or "WordEllipsis" (default is None).
[System.Windows.Controls.ScrollViewer control can be used for scrolling.]
The ScrollViewer control is introduced as the standard way to add scroll bars to a region of content. Its content property is set to the element that needs scrolling, and VerticalScrollBarVisibility and HorizontalScrollBarVisibility properties control the display of scroll bars.
π Example:
<Window Title="Using ScrollViewer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<ScrollViewer>
<StackPanel>
... <!-- Content that may overflow -->
</StackPanel>
</ScrollViewer>
</Window>
[Scaling β Viewbox]
While scrolling is more common, some scenarios (e.g., card games) require scaling. ScaleTransform works relative to an elementβs own size, not the available container size. The Viewbox control is a Decorator class (like Border) that acts like a panel but can only have one child. It stretches its child content to fill the available space. The Stretch property controls how stretching occurs: None (no stretching), Fill (distort to fill), Uniform (maintain aspect ratio, default), and UniformToFill (cropped). The StretchDirection property controls the direction of scaling: UpOnly, DownOnly, or Both (default).
π Definition β Viewbox: A WPF control that scales its single child element to fill the available space, preserving or distorting aspect ratio based on the Stretch and StretchDirection properties.
π Properties:
Stretch="Uniform"(default) β scales proportionally to fill the available space without cropping.Stretch="Fill"β stretches non-uniformly to completely fill the space.StretchDirection="DownOnly"β only shrinks content, never enlarges it.
π Example:
<Window Title="Using Viewbox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Viewbox Stretch="Uniform" StretchDirection="DownOnly">
<StackPanel>
... <!-- Content scales to fit the window while maintaining proportions and never enlarging beyond original size -->
</StackPanel>
</Viewbox>
</Window>
π‘ Why this matters: Viewbox is essential for creating responsive UIs where content must fit different screen sizes without distortion, such as diagrams, charts, or game interfaces.
β Key Takeaways
The most critical points to remember are: (1) SharedSizeGroup with IsSharedSizeScope enables synchronized column/row resizing across multiple grids, essential for creating consistent layouts; (2) Content overflow can be handled by five methods: clipping (default with ClipToBounds), scrolling (ScrollViewer), scaling (Viewbox), wrapping (WrapPanel for non-text), and trimming (text with TextTrimming); (3) The ScrollViewer control wraps content and provides scroll bars controlled by VerticalScrollBarVisibility and HorizontalScrollBarVisibility; (4) The Viewbox control scales its single child using the Stretch property (None, Fill, Uniform, UniformToFill) and StretchDirection property (UpOnly, DownOnly, Both); (5) Clipping occurs before RenderTransform, so you cannot recover clipped content with a transform β use Viewbox or ScrollViewer instead.
π§ Quick Revision Questions
- What is the purpose of the
SharedSizeGroupproperty in a Grid, and what must be set toTrueto enable it across multiple grids? - List the five methods for handling content overflow in WPF.
- What is the difference between
TextTrimming="CharacterEllipsis"andTextTrimming="WordEllipsis"? - Which WPF control is used to add scrolling to a region, and which properties control scroll bar visibility?
- If you want to scale a UI element to fill its parent container while maintaining its aspect ratio, which
Stretchvalue should you use in aViewbox?
π Lecture 21 β Application with Collapsible, Dockable, Resizable Panes and Input Events
π Overview: This lecture covers the implementation of a complex WPF interface featuring collapsible, dockable, and resizable panes using multiple Grid layers and SharedSizeGroup. It then introduces the concept of routed events, explaining their routing strategies, how they differ from .NET events, and demonstrates them with keyboard and mouse event handling.
ποΈ Topics Covered
The lecture explains how to build a multi-pane interface using three overlapping Grid layers with SharedSizeGroup to maintain synchronization when docked. It covers the XAML structure with DockPanel, rotating button bars, and gridsplitters for resizing. The code-behind manages pane docking/undocking through visibility toggling, cloned column definitions, and Z-order manipulation. The second half introduces routed events as an extra layer on .NET events, covering tunneling, bubbling, and direct routing strategies, with event handlers that access Source and OriginalSource properties.
π Lecture Summary
Building a Multi-Pane Interface with Grid Layers
Because splitters are needed, a Grid is a reasonable approach. The interface uses three independent Grids to allow overlapping. SharedSizeGroup keeps them in sync when docked. When docking, cells are added or removed. Z-order between layer 1 and layer 2 ensures that the undocked pane appears on top. All three grids are placed in another Grid of a single row and column.
The XAML structure begins with a DockPanel containing a Menu docked at the top. A StackPanel named "buttonbar" is docked to the right edge, with a RotateTransform applied at 90 degrees to display buttons vertically. Inside the DockPanel, a parent Grid named "parentgrid" has IsSharedSizeScope="True" with two column definitions (5* and 364*).
π Definition β SharedSizeScope: A property that allows multiple Grid elements to share the same column or row sizing based on a shared size group name, keeping them synchronized.
Layer 0 is the main content area with Grid.ColumnSpan="2". Layer 1 and Layer 2 each contain a column definition with SharedSizeGroup ("column1" and "column2" respectively) and Width="Auto". Each has a Grid in column 1 containing a header with a pin button and pane-specific content, plus a GridSplitter of Width 5 with HorizontalAlignment="Left" for resizing.
π Formula: SharedSizeGroup β Columns with the same SharedSizeGroup name across different Grids maintain the same width automatically.
Code-Behind: Dock and Undock Logic
The code-behind class mainwindow inherits from Window. Three dummy ColumnDefinition objects are created in the constructor for managing docked columns: column1cloneforlayer0, column2cloneforlayer0, and column2cloneforlayer1, each assigned a SharedSizeGroup.
The Dockpane method toggles a pane from undocked to docked state. It hides the corresponding pane button (Visibility.Collapsed), changes the pin image source to "pin.gif", and adds the appropriate cloned column to layer 0. If the other pane is already docked, it also adds the cloned column to layer 1.
The Undockpane method reverses the process. It shows the pane layer (Visibility.Visible), reveals the pane button, changes the pin image to "pinhorizontal.gif", and removes the cloned columns from layers 0 and 1. The Remove method silently ignores columns that are not present.
π‘ Why this matters: The cloned column approach allows the docked pane to occupy real column space when docked, while the SharedSizeGroup ensures the column widths remain consistent between root states.
Mouse Enter Event Handling for Auto-Show and Z-Order
When the mouse enters a pane button, the corresponding layer becomes visible (Visibility.Visible). The Z-order is adjusted using Grid.SetZIndex to ensure the active pane is on top (ZIndex = 1) while the other is at ZIndex = 0. If the other pane is undocked (its button is visible), it gets collapsed to prevent overlap.
When the mouse enters Layer 0 (the main content area), any undocked panes are collapsed. Similarly, when entering a docked pane, the other undocked pane is collapsed to maintain focus.
Introduction to Routed Events
Routed events are an extra layer on top of .NET events, similar to how dependency properties extend .NET properties. They can travel up or down the visual or logical tree, helping applications remain oblivious to the visual tree structure. For example, a Button exposes a Click event based on MouseLeftButtonDown and KeyDown, but actually a visual child like ButtonChrome or TextBlock fires the event. The event travels up the tree, and the Button eventually sees it.
Routed events are an implementation feature (not a language feature) supported by XAML. They use public static RoutedEvent fields, conventionally suffixed with "Event", registered in a static constructor, with a .NET event wrapper (which should not perform additional logic).
π Definition β RoutedEvent: An event that can be routed through multiple handlers in a visual or logical tree, supporting tunnel, bubble, or direct strategies.
Registering a Routed Event
In the Button class, the Click event is declared as public static readonly RoutedEvent ClickEvent. In the static constructor, it is registered using EventManager.RegisterRoutedEvent("Click", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(Button)). The .NET event wrapper uses AddHandler and RemoveHandler from UIElement. The event is raised in OnMouseLeftButtonDown using RaiseEvent(new RoutedEventArgs(Button.ClickEvent, this)).
Routing Strategies
Three routing strategies exist:
- Tunneling: Event travels from the root element down to the source element, or until marked as handled. Tunneling events are prefixed with Preview (e.g., PreviewMouseMove comes before MouseMove).
- Bubbling: Event travels from the source element up to the root, or until marked as handled. Most input events use bubbling.
- Direct: Event is raised only on the source element, similar to standard .NET events, but still participates in routed event features like event triggers.
π Definition β RoutingStrategy.Bubble: The event starts at the source element and travels upward through the visual tree to the root. π Definition β RoutingStrategy.Tunnel: The event starts at the root element and travels downward through the visual tree to the source.
Event Handler Parameters
Handlers for routed events receive a System.Object parameter (the sender to which the handler was attached) and System.EventArgs containing:
- Source: The element in the logical tree that originally raised the event
- OriginalSource: The element in the visual tree that raised the event (e.g., a TextBlock on top of a Button)
- RoutedEvent: The actual routed event object (e.g., Button.ClickEvent), useful when the same handler is used for multiple events.
By convention, actions are only taken on the bubbling event, so the tunneling (Preview) event gives a chance to cancel or modify the event (e.g., using PreviewKeyDown for restrictive input in a TextBox).
Example: Mouse Right Button Down Handler
The example shows an About dialog window with the MouseRightButtonDown event attached to the Window. The event handler aboutdialog_mouserightbuttondown displays information about the event in the window title: "Source = " plus the type name of e.Source, "OriginalSource = " plus the type name of e.OriginalSource, and the timestamp.
It then casts the Source to a Control and toggles a border around it β setting a 5-pixel thick black border if none exists, or removing it otherwise. This demonstrates how the same handler can respond to events coming from any child element in the visual tree.
β Key Takeaways
A student must understand how to implement a multi-pane docking interface using Grid layers with SharedSizeGroup, cloned column definitions, and Z-order management for overlapped elements. The concept of routed events is fundamental β they travel through the visual/logical tree using tunneling (Preview prefix, root to source) or bubbling (source to root) strategies, allowing parent elements to handle events from their children. The Source property refers to the logical tree element that raised the event, while OriginalSource refers to the visual tree element. Most input events like mouse and keyboard follow this routed event pattern, enabling simplified event handling without custom code on inner content.
π§ Quick Revision Questions
- Why are three overlapping Grid layers used in this application instead of a single Grid with nested elements?
- What is the purpose of
SharedSizeGroupandIsSharedSizeScopein the docking interface implementation? - How does the
Dockpanemethod ensure that a docked pane occupies the correct column space in both layers? - What is the difference between tunneling and bubbling routing strategies, and how does the naming convention distinguish them?
- In the mouse right button down example, why does
OriginalSourcediffer fromSource, and what scenario would cause this difference?