Getting a start point grid in WPF with C# means two things: capturing a starting cell from mouse input, and rendering a coordinate grid that tells you where that point sits. Build the grid from a UniformGrid or a set of Line shapes in a Canvas, put an ItemsControl or a Rectangle overlay on top for hit detection, then convert the click position with Mouse.GetPosition into row and column indices. The key condition is simple: decide up front whether your grid is a fixed cell size in device-independent pixels or a normalized percentage grid, because that choice determines every conversion you write afterward. This article walks through both a fast declarative version and a fully computed version, with the arithmetic behind each.
I'll assume .NET 6 or later with WPF, a Grid or Canvas layout, and a basic event-handler workflow. Everything below works in .NET Framework 4.8 as well; the WPF APIs involved haven't changed.
Decide What "Start Point" and "Grid" Mean Before Writing Code
Different projects mean different things by this phrase, and the name collides. In graph and pathfinding code, a start point grid is a two-dimensional array marking legal start cells. In UI tooling, it's an on-screen lattice you click to pick an origin. In layout work, it's a UniformGrid panel used as a coordinate substrate. Sorting this out first saves you from building the wrong abstraction.
Ask three questions. First, is the grid fixed-count (say 20 by 12 cells regardless of window size) or fixed-size (each cell is 24 pixels, count follows the window)? Second, is the start point an integer cell index, a fractional coordinate in grid space, or a snapped corner? Third, does the grid need to survive resizing, zooming, or DPI changes with its logical coordinates intact?
A grid with fixed count and a normalized coordinate system is the most robust for editors, because a cell index stays valid when the window resizes. A fixed-pixel grid is simpler for drawing programs where one cell always equals 10 device-independent pixels. Most confusion in WPF grid projects comes from mixing these two models halfway through, so pick one and document the choice in a comment at the top of your code.
For the walkthrough, I'll build a fixed-pixel grid because the conversion arithmetic is easier to verify, then show the normalized variant.
The Minimal Working Version: A UniformGrid With Click Capture
This is the fastest path to a functioning start-point picker. A UniformGrid divides its available area into equal cells without any manual math, and a Rectangle inside each cell acts as a hit target.
The XAML places a UniformGrid inside a bordered container, with Rows and Columns set, and an ItemsControl bound to a collection of cell view models. If you don't need per-cell state yet, you can skip the items control and use a single overlay element, which is covered in the next section.
Prerequisites: a WPF project targeting a supported .NET version, one window, and no third-party layout packages. Steps:
1: Add a UniformGrid with Rows="12" and Columns="20" inside a Border with a visible BorderBrush. 2: Attach a PreviewMouseLeftButtonDown handler to the Border. 3: In the handler, call e.GetPosition(border) to get the click in the border's coordinate space. 4: Compute col = (int)(p.X / (border.ActualWidth / columns)) and row = (int)(p.Y / (border.ActualHeight / rows)). 5: Clamp both indices with Math.Clamp to 0..columns-1 and 0..rows-1, because the right and bottom edges can produce an index equal to the count. 6: Store the result in two properties and raise a change notification.
The success check: click each corner. Top-left should report (0,0), bottom-right should report (19,11), and a click exactly on a cell boundary should land in the cell to the right or below, consistently. If corner clicks report an off-by-one index, your clamp is missing or your denominator uses the wrong dimension.
The failure mode to watch: ActualWidth is zero in the constructor and during Loaded edge cases, so never compute grid geometry in the constructor. Do the first calculation in Loaded or in the click handler itself. Also, UniformGrid distributes remainder pixels unevenly, so cell widths can differ by one device-independent pixel. For pixel-perfect editors, don't use UniformGrid for hit testing; use the computed approach below.
Drawing a Real Grid With Lines and Canvas
When you need visible gridlines, spines, labels, or a background that the user can zoom, drawing Line elements in a Canvas gives full control. The cost is that you manage the geometry yourself.
A practical structure: a Canvas for gridlines, then a Canvas or Rectangle layer for the click surface, then a Canvas for the start-point marker. Keeping these as siblings in a parent Grid avoids z-index surprises.
For each vertical line at index i from 0 to columns, set X1 = X2 = i * cellWidth, Y1 = 0, Y2 = totalHeight. Horizontal lines follow the same pattern with the axes swapped. Set Stroke, StrokeThickness, and optionally SnapsToDevicePixels="True" to prevent half-pixel blur.
Two gotchas worth stating plainly. First, a Canvas does not clip its children, so lines drawn past the bounds will spill; set a ClipToBounds container or compute an explicit RectangleGeometry clip. Second, if you redraw on every SizeChanged, you'll create and discard hundreds of Line objects per resize event. Either reuse a pool of lines and update their endpoints, or draw the grid once into a DrawingBrush or DrawingVisual and let the visual layer scale it. The pooled approach is roughly an order of magnitude cheaper in allocations for a 40-by-40 grid, though I'd treat that as an engineering expectation rather than a measured benchmark on your machine.
An optional sensory note for anyone building a design tool: a 1-pixel line at 100 percent zoom looks crisp, but on a high-DPI display with fractional scaling it can smear. Snap endpoints to whole device-independent pixels and the lines stay sharp.
Capturing Click Coordinates and Converting Them to a Grid Origin
Mouse.GetPosition(element) returns a Point in the coordinate space of the named element, after applying that element's render transforms. That last clause matters: if the grid sits inside a scaled Viewbox or a ScaleTransform, the returned point is in the untransformed local space, which is usually what you want but occasionally isn't.
The general conversion from a local point to fractional grid coordinates is:
colFraction = (p.X - originX) / cellWidth rowFraction = (p.Y - originY) / cellHeight
where originX and originY are the top-left of the grid's content area, excluding padding and border thickness. For a border with BorderThickness="1", subtract one from both axes or place the grid content in the border's child, which already excludes the border.
If you're using a transform on the content, prefer e.GetPosition(gridCanvas) where gridCanvas is the direct child that holds the lines. That way padding and borders are already handled by the framework.
Then floor the fractions for a cell index, or keep them fractional if the start point should slide continuously. A good API returns both: CellRow, CellColumn, and PointInCell with values in 0..1 on each axis. That lets a caller snap to cell centers, cell corners, or an arbitrary anchor without recomputing anything.
Validation matters more than people expect. Points outside the bounds produce negative indices or indices beyond the count when the click comes from a child element that overflows, so always test p.X >= 0 && p.X < width && p.Y >= 0 && p.Y < height before converting.
Wrapping the Grid in a Reusable C# Control
Once the raw math works, promote it to a small custom control so the conversion logic lives in one place. Derive from FrameworkElement (not UserControl) if you're drawing lines yourself and want maximum control over rendering; derive from Control with a template if you want theming.
Expose dependency properties for CellWidth, CellHeight, Columns, Rows, and StartPoint (a Point or a small record with row, column, and sub-cell offset). Expose a read-only GridChanged event or a RoutedEvent for downstream consumers. Override OnRender to draw the grid lines with a DrawingContext if you're after performance, which is the idiomatic WPF path and avoids the visual tree cost entirely.
OnRender drawing is the right default for a grid that's purely visual. Inside it, loop over the line positions and call drawingContext.DrawLine(pen, p1, p2). The result is re-rendered only when InvalidateVisual is called, which the framework does for size changes if you wire it properly. For a 40 by 40 grid, that's 82 line draws, which is trivial.
One failure case: if OnRender reads a mutable collection of gridlines that you modify after the initial call, WPF won't call it again unless invalidated. Call InvalidateVisual whenever a dependency property changes; the property system's invalidation can be wired via FrameworkPropertyMetadata with AffectsRender set, which is a cleaner mechanism than manual invalidation.
A specific limit: at very high zoom levels, thousands of lines degrade both render time and anti-aliasing quality. Beyond roughly a few thousand visible lines, switch to a tiled DrawingBrush that repeats a single cell pattern, or cull lines outside the viewport before drawing. Culling is the simpler of the two and effectively free.
Two Coordinate Systems: Fixed-Pixel and Normalized Grids
The distinction deserves its own treatment because it's the source of most silent bugs. A fixed-pixel grid has cell width in device-independent pixels that never change; when the window resizes, the number of visible cells changes but a cell index always refers to the same physical size. A normalized grid has a fixed count; when the window resizes, cells stretch and stale index-to-position conversions become invalid if you cached them.
| Criterion | Fixed-pixel grid | Normalized grid |
|---|---|---|
| Cell size | Constant in DIPs | Depends on control size |
| Cells across | Varies with window | Constant count |
| Index stability on resize | Stable | Cell bounds move |
| Best for | Drawing, tile editors, pixel tools | Dashboards, layouts, fixed slots |
| Conversion to pixels | index * cellSize | index * (width / count) |
| Typical failure | Partial cells at edges | Off-by-one at right/bottom edge |
Convert between them deliberately: an index in one system can't be directly expressed in the other without knowing the current container size. If your start point must remain valid across a resize, store it in normalized coordinates and render by multiplying by the current size.
For mobile-style responsive layouts, normalized is usually the correct choice. For CAD or pixel editors, fixed-pixel is correct. Don't try to have both without an explicit conversion layer, because half-normalized code is where off-by-one errors breed.
Hit-Testing, Snapping, and Selecting a Start Point
Hit testing answers "which element is under this point," while snapping answers "which grid location does this point round to." They're related but distinct.
For hit testing, use Mouse.GetPosition on the container and conversion math, or if you've built child elements per cell, use VisualTreeHelper.HitTest and walk up from the result to find the tagged cell. The conversion approach is faster and doesn't require per-cell elements, so it's the default.
For snapping, choose an anchor rule: nearest grid intersection, cell center, or cell top-left. Nearest intersection is Math.Round(fraction) * cellSize; cell center is (Math.Floor(fraction) + 0.5) * cellSize; cell top-left is Math.Floor(fraction) * cellSize. Pick the rule that matches user expectations: layout designers expect intersection snapping, tile editors expect cell top-left.
Some checks to verify success: click near a boundary and confirm the point snaps to the intended side; drag into the negative region and confirm it's rejected or clamped per your spec; resize the window and click the same physical location; in a normalized grid, the index should remain constant only if you convert to normalized before storing.
One subtle pitfall with Math.Round is banker's rounding, which rounds .5 to the nearest even number. If that's not what you want for a boundary, use Math.Round(value, MidpointRounding.AwayFromZero).
Handling DPI, Resizing, and Redraw Edge Cases
WPF's device-independent pixel system handles most DPI concerns for you, but not all. At 150 percent scaling, a 1-DIP line is 1.5 physical pixels, which anti-aliases. If crispness matters, snap to physical pixels by querying VisualTreeHelper.GetDpi(this) in .NET 4.6.2+ and adjusting stroke positions accordingly. This is more code than most projects need, but for grid editors it's worth considering.
For resizing, the standard pattern is to wire SizeChanged and mark the affected geometry as invalid. If you're using OnRender, the AffectsRender metadata flag handles this automatically. If you're using Canvas children, you must recompute line endpoints manually.
Retained-mode WPF will coalesce resize renders, but event handlers calling InvalidateVisual on every pixel change can still cause visible lag on grids with hundreds of elements. Test at your worst realistic size: a 1920 by 1080 window at 150 percent DPI with 40 by 40 cells. If it repaints slower than you'd like, cull off-screen lines and reuse pens.
Another edge: ActualWidth and ActualHeight can be 0 when the control isn't yet in a visual tree. Every conversion method should return safely instead of dividing by zero. A simple guard at the top of the conversion helper is preferable to a try/catch, and it makes unit testing easier, since you can test the conversion without a live visual tree.
A Graph-Style Start Point Grid in Code
If your goal is actually a data structure rather than a UI, the C# side is a two-dimensional array or a flat array accessed via index arithmetic. For a grid of M by N cells, bool[,] walkable = new bool[rows, columns], and a start point is a (row, col) record.
The conversion from screen to data index is the same as above but is often done once, then stored. A useful small design: a GridPoint record struct with Row, Column, and optionally SubCell for fractional start points. Validate against 0 <= Row < rows when constructing it and throw, since an out-of-range start point will otherwise travel deep into pathfinding code before failing.
A worked example of the arithmetic, with illustrative inputs. Suppose the drawing area is 800 by 480 DIPs, you want 20 by 12 cells, and the user clicks at local point (317, 219). Cell width is 800/20 = 40 DIPs, cell height is 480/12 = 40 DIPs. Column fraction is 317/40 = 7.925, row fraction is 219/40 = 5.475. Floored, that's column 7, row 5. The point sits 0.925 across and 0.475 down inside that cell. Say your anchor is the cell center: 7.5 × 40 = 300 and 5.5 × 40 = 220. Snap the cursor to (300, 220). Every number here is reproducible with a calculator, so you can verify a conversion helper against this exact case.
If you also need to go the other way, cell index to screen center, the formula is screenX = (col + 0.5) * cellWidth. That symmetry is why I keep both directions in the same helper class and test both, since rounding mismatches between them are the usual root cause of "the marker is off by half a cell."
Where This Usually Goes Wrong
A few failure patterns recur across WPF grid projects. The most common is coordinate space confusion: calling GetPosition on the window and then dividing by a component's width that excludes padding. Inconsistent results usually trace back to a mismatch between where the point is measured and where the size is measured; fixing the call site to name the exact container resolves it.
The second is edge quantization: clicks near the right or bottom border produce an index equal to the count, which later causes an out-of-range exception or a marker drawn halfway off-screen. Clamping with Math.Clamp to count - 1 is the minimum fix; the complete fix also takes the point's local position into account for the marker.
Third, redraw storms: rebuilding the visual tree on every pointer movement, which is common when a start-point picker shares event handlers with a drawing routine. Only rebuild when the geometry changes; otherwise, move a single marker.
Fourth, using Margin on cells inside a UniformGrid to simulate gaps. This shifts the effective cell content but not the uniform division, so the visible gap doesn't match the click regions. Draw gridlines with spacing or use a Canvas with explicit positions if you need visual gaps that match hit testing.
Fifth, storing the start point as a screen Point instead of a grid-relative coordinate. The next resize invalidates every stored value, and the bug appears much later in a different module. Store logical coordinates.
When to stop and bring in help: if you're fighting a layout issue that only appears under a specific Viewbox/RenderTransform combination and you've ruled out coordinate space confusion, the transform stack likely needs a specialist review. WPF's rendering transforms are subtle, and a five-minute pairing session with someone fluent in them can save hours of guesswork. Similarly, if you're building a commercial editor and grid performance has already survived culling and visual pooling, the remaining wins are in the rendering architecture, not the individual conversions.
FAQ
Does this approach work for a start point that isn't on a cell boundary? Yes. Keep the fractional column and row instead of flooring them, and store the anchor as a Point. The conversion math is identical; you just don't lose the fraction.
What about right-to-left cultures or mirrored layouts? A grid in an RTL window flips the visual x-axis. Either mirror the coordinate basis explicitly in the conversion helper, or place the grid in a container with FlowDirection="LeftToRight" and mirror the labels. Be deliberate about which you choose, because it affects stored indices.
Can I use this in WinUI or MAUI? The layout and pointer APIs differ, but the grid math carries over. In WinUI 3, PointerRoutedEventArgs.GetCurrentPoint returns a Point in the sender's space, and the arithmetic is the same. WPF-specific details like OnRender and VisualTreeHelper have different but analogous counterparts.