Related
I want to write text vertically inside of a border element. As shown in this picture.
I've tried using RenderTransform with this code
<Border Width="80"
Background="Teal">
<TextBlock Text="CATEGORIES"
Foreground="White"
FontFamily="Segoe UI Black"
FontSize="30">
<TextBlock.RenderTransform>
<RotateTransform Angle="-90" />
</TextBlock.RenderTransform>
</TextBlock>
</Border>
This rotates the text vertically but the TextBlock takes the old values of height and width before Transform and doesn't display the text completely. So the text is cut off after 80 pixels (width of the border element). While searching I found using LayoutTransform can solve the problem but it is not available in UWP apps. How to do this in UWP XAML?
This worked for me on UWP as well. Just use the class posted here instead of the one from the post. And also copy the style from the blog post.
EDIT: The onedrive link no longer works. So I am posting the code here.
Create a new class LayoutTransformer
using System;
using System.Diagnostics.CodeAnalysis;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
namespace Common
{
/// <summary>
/// Represents a control that applies a layout transformation to its Content.
/// </summary>
/// <QualityBand>Preview</QualityBand>
[TemplatePart(Name = TransformRootName, Type = typeof(Grid))]
[TemplatePart(Name = PresenterName, Type = typeof(ContentPresenter))]
public sealed class LayoutTransformer : ContentControl
{
/// <summary>
/// Name of the TransformRoot template part.
/// </summary>
private const string TransformRootName = "TransformRoot";
/// <summary>
/// Name of the Presenter template part.
/// </summary>
private const string PresenterName = "Presenter";
/// <summary>
/// Gets or sets the layout transform to apply on the LayoutTransformer
/// control content.
/// </summary>
/// <remarks>
/// Corresponds to UIElement.LayoutTransform.
/// </remarks>
public Transform LayoutTransform
{
get { return (Transform)GetValue(LayoutTransformProperty); }
set { SetValue(LayoutTransformProperty, value); }
}
/// <summary>
/// Identifies the LayoutTransform DependencyProperty.
/// </summary>
public static readonly DependencyProperty LayoutTransformProperty = DependencyProperty.Register(
"LayoutTransform", typeof(Transform), typeof(LayoutTransformer), new PropertyMetadata(null, LayoutTransformChanged));
/// <summary>
/// Gets the child element being transformed.
/// </summary>
private FrameworkElement Child
{
get
{
// Preferred child is the content; fall back to the presenter itself
return (null != _contentPresenter) ?
(_contentPresenter.Content as FrameworkElement ?? _contentPresenter) :
null;
}
}
// Note: AcceptableDelta and DecimalsAfterRound work around double arithmetic rounding issues on Silverlight.
private const double AcceptableDelta = 0.0001;
private const int DecimalsAfterRound = 4;
private Panel _transformRoot;
private ContentPresenter _contentPresenter;
private MatrixTransform _matrixTransform;
private Matrix _transformation;
private Size _childActualSize = Size.Empty;
public LayoutTransformer()
{
// Associated default style
DefaultStyleKey = typeof(LayoutTransformer);
// Can't tab to LayoutTransformer
IsTabStop = false;
#if SILVERLIGHT
// Disable layout rounding because its rounding of values confuses things
UseLayoutRounding = false;
#endif
}
/// <summary>
/// Builds the visual tree for the LayoutTransformer control when a new
/// template is applied.
/// </summary>
protected override void OnApplyTemplate()
{
// Apply new template
base.OnApplyTemplate();
// Find template parts
_transformRoot = GetTemplateChild(TransformRootName) as Grid;
_contentPresenter = GetTemplateChild(PresenterName) as ContentPresenter;
_matrixTransform = new MatrixTransform();
if (null != _transformRoot)
{
_transformRoot.RenderTransform = _matrixTransform;
}
// Apply the current transform
ApplyLayoutTransform();
}
/// <summary>
/// Handles changes to the Transform DependencyProperty.
/// </summary>
/// <param name="o">Source of the change.</param>
/// <param name="e">Event args.</param>
private static void LayoutTransformChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
// Casts are safe because Silverlight is enforcing the types
((LayoutTransformer)o).ProcessTransform((Transform)e.NewValue);
}
/// <summary>
/// Applies the layout transform on the LayoutTransformer control content.
/// </summary>
/// <remarks>
/// Only used in advanced scenarios (like animating the LayoutTransform).
/// Should be used to notify the LayoutTransformer control that some aspect
/// of its Transform property has changed.
/// </remarks>
public void ApplyLayoutTransform()
{
ProcessTransform(LayoutTransform);
}
/// <summary>
/// Processes the Transform to determine the corresponding Matrix.
/// </summary>
/// <param name="transform">Transform to process.</param>
private void ProcessTransform(Transform transform)
{
// Get the transform matrix and apply it
_transformation = RoundMatrix(GetTransformMatrix(transform), DecimalsAfterRound);
if (null != _matrixTransform)
{
_matrixTransform.Matrix = _transformation;
}
// New transform means re-layout is necessary
InvalidateMeasure();
}
/// <summary>
/// Walks the Transform(Group) and returns the corresponding Matrix.
/// </summary>
/// <param name="transform">Transform(Group) to walk.</param>
/// <returns>Computed Matrix.</returns>
private Matrix GetTransformMatrix(Transform transform)
{
if (null != transform)
{
// WPF equivalent of this entire method:
// return transform.Value;
// Process the TransformGroup
TransformGroup transformGroup = transform as TransformGroup;
if (null != transformGroup)
{
Matrix groupMatrix = Matrix.Identity;
foreach (Transform child in transformGroup.Children)
{
groupMatrix = MatrixMultiply(groupMatrix, GetTransformMatrix(child));
}
return groupMatrix;
}
// Process the RotateTransform
RotateTransform rotateTransform = transform as RotateTransform;
if (null != rotateTransform)
{
double angle = rotateTransform.Angle;
double angleRadians = (2 * Math.PI * angle) / 360;
double sine = Math.Sin(angleRadians);
double cosine = Math.Cos(angleRadians);
return new Matrix(cosine, sine, -sine, cosine, 0, 0);
}
// Process the ScaleTransform
ScaleTransform scaleTransform = transform as ScaleTransform;
if (null != scaleTransform)
{
double scaleX = scaleTransform.ScaleX;
double scaleY = scaleTransform.ScaleY;
return new Matrix(scaleX, 0, 0, scaleY, 0, 0);
}
// Process the SkewTransform
SkewTransform skewTransform = transform as SkewTransform;
if (null != skewTransform)
{
double angleX = skewTransform.AngleX;
double angleY = skewTransform.AngleY;
double angleXRadians = (2 * Math.PI * angleX) / 360;
double angleYRadians = (2 * Math.PI * angleY) / 360;
return new Matrix(1, angleYRadians, angleXRadians, 1, 0, 0);
}
// Process the MatrixTransform
MatrixTransform matrixTransform = transform as MatrixTransform;
if (null != matrixTransform)
{
return matrixTransform.Matrix;
}
// TranslateTransform has no effect in LayoutTransform
}
// Fall back to no-op transformation
return Matrix.Identity;
}
/// <summary>
/// Provides the behavior for the "Measure" pass of layout.
/// </summary>
/// <param name="availableSize">The available size that this element can give to child elements.</param>
/// <returns>The size that this element determines it needs during layout, based on its calculations of child element sizes.</returns>
protected override Size MeasureOverride(Size availableSize)
{
FrameworkElement child = Child;
if ((null == _transformRoot) || (null == child))
{
// No content, no size
return Size.Empty;
}
//DiagnosticWriteLine("MeasureOverride < " + availableSize);
Size measureSize;
if (_childActualSize == Size.Empty)
{
// Determine the largest size after the transformation
measureSize = ComputeLargestTransformedSize(availableSize);
}
else
{
// Previous measure/arrange pass determined that Child.DesiredSize was larger than believed
//DiagnosticWriteLine(" Using _childActualSize");
measureSize = _childActualSize;
}
// Perform a mesaure on the _transformRoot (containing Child)
//DiagnosticWriteLine(" _transformRoot.Measure < " + measureSize);
_transformRoot.Measure(measureSize);
//DiagnosticWriteLine(" _transformRoot.DesiredSize = " + _transformRoot.DesiredSize);
// WPF equivalent of _childActualSize technique (much simpler, but doesn't work on Silverlight 2)
// // If the child is going to render larger than the available size, re-measure according to that size
// child.Arrange(new Rect());
// if (child.RenderSize != child.DesiredSize)
// {
// _transformRoot.Measure(child.RenderSize);
// }
// Transform DesiredSize to find its width/height
Rect transformedDesiredRect = RectTransform(new Rect(0, 0, _transformRoot.DesiredSize.Width, _transformRoot.DesiredSize.Height), _transformation);
Size transformedDesiredSize = new Size(transformedDesiredRect.Width, transformedDesiredRect.Height);
// Return result to allocate enough space for the transformation
//DiagnosticWriteLine("MeasureOverride > " + transformedDesiredSize);
return transformedDesiredSize;
}
/// <summary>
/// Provides the behavior for the "Arrange" pass of layout.
/// </summary>
/// <param name="finalSize">The final area within the parent that this element should use to arrange itself and its children.</param>
/// <returns>The actual size used.</returns>
/// <remarks>
/// Using the WPF paramater name finalSize instead of Silverlight's finalSize for clarity
/// </remarks>
protected override Size ArrangeOverride(Size finalSize)
{
FrameworkElement child = Child;
if ((null == _transformRoot) || (null == child))
{
// No child, use whatever was given
return finalSize;
}
//DiagnosticWriteLine("ArrangeOverride < " + finalSize);
// Determine the largest available size after the transformation
Size finalSizeTransformed = ComputeLargestTransformedSize(finalSize);
if (IsSizeSmaller(finalSizeTransformed, _transformRoot.DesiredSize))
{
// Some elements do not like being given less space than they asked for (ex: TextBlock)
// Bump the working size up to do the right thing by them
//DiagnosticWriteLine(" Replacing finalSizeTransformed with larger _transformRoot.DesiredSize");
finalSizeTransformed = _transformRoot.DesiredSize;
}
//DiagnosticWriteLine(" finalSizeTransformed = " + finalSizeTransformed);
// Transform the working size to find its width/height
Rect transformedRect = RectTransform(new Rect(0, 0, finalSizeTransformed.Width, finalSizeTransformed.Height), _transformation);
// Create the Arrange rect to center the transformed content
Rect finalRect = new Rect(
-transformedRect.Left + ((finalSize.Width - transformedRect.Width) / 2),
-transformedRect.Top + ((finalSize.Height - transformedRect.Height) / 2),
finalSizeTransformed.Width,
finalSizeTransformed.Height);
// Perform an Arrange on _transformRoot (containing Child)
//DiagnosticWriteLine(" _transformRoot.Arrange < " + finalRect);
_transformRoot.Arrange(finalRect);
//DiagnosticWriteLine(" Child.RenderSize = " + child.RenderSize);
// This is the first opportunity under Silverlight to find out the Child's true DesiredSize
if (IsSizeSmaller(finalSizeTransformed, child.RenderSize) && (Size.Empty == _childActualSize))
{
// Unfortunately, all the work so far is invalid because the wrong DesiredSize was used
//DiagnosticWriteLine(" finalSizeTransformed smaller than Child.RenderSize");
// Make a note of the actual DesiredSize
_childActualSize = new Size(child.ActualWidth, child.ActualHeight);
//DiagnosticWriteLine(" _childActualSize = " + _childActualSize);
// Force a new measure/arrange pass
InvalidateMeasure();
}
else
{
// Clear the "need to measure/arrange again" flag
_childActualSize = Size.Empty;
}
//DiagnosticWriteLine(" _transformRoot.RenderSize = " + _transformRoot.RenderSize);
// Return result to perform the transformation
//DiagnosticWriteLine("ArrangeOverride > " + finalSize);
return finalSize;
}
/// <summary>
/// Compute the largest usable size (greatest area) after applying the transformation to the specified bounds.
/// </summary>
/// <param name="arrangeBounds">Arrange bounds.</param>
/// <returns>Largest Size possible.</returns>
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Closely corresponds to WPF's FrameworkElement.FindMaximalAreaLocalSpaceRect.")]
private Size ComputeLargestTransformedSize(Size arrangeBounds)
{
//DiagnosticWriteLine(" ComputeLargestTransformedSize < " + arrangeBounds);
// Computed largest transformed size
Size computedSize = Size.Empty;
// Detect infinite bounds and constrain the scenario
bool infiniteWidth = double.IsInfinity(arrangeBounds.Width);
if (infiniteWidth)
{
arrangeBounds.Width = arrangeBounds.Height;
}
bool infiniteHeight = double.IsInfinity(arrangeBounds.Height);
if (infiniteHeight)
{
arrangeBounds.Height = arrangeBounds.Width;
}
// Capture the matrix parameters
double a = _transformation.M11;
double b = _transformation.M12;
double c = _transformation.M21;
double d = _transformation.M22;
// Compute maximum possible transformed width/height based on starting width/height
// These constraints define two lines in the positive x/y quadrant
double maxWidthFromWidth = Math.Abs(arrangeBounds.Width / a);
double maxHeightFromWidth = Math.Abs(arrangeBounds.Width / c);
double maxWidthFromHeight = Math.Abs(arrangeBounds.Height / b);
double maxHeightFromHeight = Math.Abs(arrangeBounds.Height / d);
// The transformed width/height that maximize the area under each segment is its midpoint
// At most one of the two midpoints will satisfy both constraints
double idealWidthFromWidth = maxWidthFromWidth / 2;
double idealHeightFromWidth = maxHeightFromWidth / 2;
double idealWidthFromHeight = maxWidthFromHeight / 2;
double idealHeightFromHeight = maxHeightFromHeight / 2;
// Compute slope of both constraint lines
double slopeFromWidth = -(maxHeightFromWidth / maxWidthFromWidth);
double slopeFromHeight = -(maxHeightFromHeight / maxWidthFromHeight);
if ((0 == arrangeBounds.Width) || (0 == arrangeBounds.Height))
{
// Check for empty bounds
computedSize = new Size(arrangeBounds.Width, arrangeBounds.Height);
}
else if (infiniteWidth && infiniteHeight)
{
// Check for completely unbound scenario
computedSize = new Size(double.PositiveInfinity, double.PositiveInfinity);
}
else if (!MatrixHasInverse(_transformation))
{
// Check for singular matrix
computedSize = new Size(0, 0);
}
else if ((0 == b) || (0 == c))
{
// Check for 0/180 degree special cases
double maxHeight = (infiniteHeight ? double.PositiveInfinity : maxHeightFromHeight);
double maxWidth = (infiniteWidth ? double.PositiveInfinity : maxWidthFromWidth);
if ((0 == b) && (0 == c))
{
// No constraints
computedSize = new Size(maxWidth, maxHeight);
}
else if (0 == b)
{
// Constrained by width
double computedHeight = Math.Min(idealHeightFromWidth, maxHeight);
computedSize = new Size(
maxWidth - Math.Abs((c * computedHeight) / a),
computedHeight);
}
else if (0 == c)
{
// Constrained by height
double computedWidth = Math.Min(idealWidthFromHeight, maxWidth);
computedSize = new Size(
computedWidth,
maxHeight - Math.Abs((b * computedWidth) / d));
}
}
else if ((0 == a) || (0 == d))
{
// Check for 90/270 degree special cases
double maxWidth = (infiniteHeight ? double.PositiveInfinity : maxWidthFromHeight);
double maxHeight = (infiniteWidth ? double.PositiveInfinity : maxHeightFromWidth);
if ((0 == a) && (0 == d))
{
// No constraints
computedSize = new Size(maxWidth, maxHeight);
}
else if (0 == a)
{
// Constrained by width
double computedHeight = Math.Min(idealHeightFromHeight, maxHeight);
computedSize = new Size(
maxWidth - Math.Abs((d * computedHeight) / b),
computedHeight);
}
else if (0 == d)
{
// Constrained by height
double computedWidth = Math.Min(idealWidthFromWidth, maxWidth);
computedSize = new Size(
computedWidth,
maxHeight - Math.Abs((a * computedWidth) / c));
}
}
else if (idealHeightFromWidth <= ((slopeFromHeight * idealWidthFromWidth) + maxHeightFromHeight))
{
// Check the width midpoint for viability (by being below the height constraint line)
computedSize = new Size(idealWidthFromWidth, idealHeightFromWidth);
}
else if (idealHeightFromHeight <= ((slopeFromWidth * idealWidthFromHeight) + maxHeightFromWidth))
{
// Check the height midpoint for viability (by being below the width constraint line)
computedSize = new Size(idealWidthFromHeight, idealHeightFromHeight);
}
else
{
// Neither midpoint is viable; use the intersection of the two constraint lines instead
// Compute width by setting heights equal (m1*x+c1=m2*x+c2)
double computedWidth = (maxHeightFromHeight - maxHeightFromWidth) / (slopeFromWidth - slopeFromHeight);
// Compute height from width constraint line (y=m*x+c; using height would give same result)
computedSize = new Size(
computedWidth,
(slopeFromWidth * computedWidth) + maxHeightFromWidth);
}
// Return result
//DiagnosticWriteLine(" ComputeLargestTransformedSize > " + computedSize);
return computedSize;
}
/// <summary>
/// Returns true if Size a is smaller than Size b in either dimension.
/// </summary>
/// <param name="a">Second Size.</param>
/// <param name="b">First Size.</param>
/// <returns>True if Size a is smaller than Size b in either dimension.</returns>
private static bool IsSizeSmaller(Size a, Size b)
{
// WPF equivalent of following code:
// return ((a.Width < b.Width) || (a.Height < b.Height));
return ((a.Width + AcceptableDelta < b.Width) || (a.Height + AcceptableDelta < b.Height));
}
/// <summary>
/// Rounds the non-offset elements of a Matrix to avoid issues due to floating point imprecision.
/// </summary>
/// <param name="matrix">Matrix to round.</param>
/// <param name="decimals">Number of decimal places to round to.</param>
/// <returns>Rounded Matrix.</returns>
private static Matrix RoundMatrix(Matrix matrix, int decimals)
{
return new Matrix(
Math.Round(matrix.M11, decimals),
Math.Round(matrix.M12, decimals),
Math.Round(matrix.M21, decimals),
Math.Round(matrix.M22, decimals),
matrix.OffsetX,
matrix.OffsetY);
}
/// <summary>
/// Implements WPF's Rect.Transform on Silverlight.
/// </summary>
/// <param name="rect">Rect to transform.</param>
/// <param name="matrix">Matrix to transform with.</param>
/// <returns>Bounding box of transformed Rect.</returns>
private static Rect RectTransform(Rect rect, Matrix matrix)
{
// WPF equivalent of following code:
// Rect rectTransformed = Rect.Transform(rect, matrix);
Point leftTop = matrix.Transform(new Point(rect.Left, rect.Top));
Point rightTop = matrix.Transform(new Point(rect.Right, rect.Top));
Point leftBottom = matrix.Transform(new Point(rect.Left, rect.Bottom));
Point rightBottom = matrix.Transform(new Point(rect.Right, rect.Bottom));
double left = Math.Min(Math.Min(leftTop.X, rightTop.X), Math.Min(leftBottom.X, rightBottom.X));
double top = Math.Min(Math.Min(leftTop.Y, rightTop.Y), Math.Min(leftBottom.Y, rightBottom.Y));
double right = Math.Max(Math.Max(leftTop.X, rightTop.X), Math.Max(leftBottom.X, rightBottom.X));
double bottom = Math.Max(Math.Max(leftTop.Y, rightTop.Y), Math.Max(leftBottom.Y, rightBottom.Y));
Rect rectTransformed = new Rect(left, top, right - left, bottom - top);
return rectTransformed;
}
/// <summary>
/// Implements WPF's Matrix.Multiply on Silverlight.
/// </summary>
/// <param name="matrix1">First matrix.</param>
/// <param name="matrix2">Second matrix.</param>
/// <returns>Multiplication result.</returns>
private static Matrix MatrixMultiply(Matrix matrix1, Matrix matrix2)
{
// WPF equivalent of following code:
// return Matrix.Multiply(matrix1, matrix2);
return new Matrix(
(matrix1.M11 * matrix2.M11) + (matrix1.M12 * matrix2.M21),
(matrix1.M11 * matrix2.M12) + (matrix1.M12 * matrix2.M22),
(matrix1.M21 * matrix2.M11) + (matrix1.M22 * matrix2.M21),
(matrix1.M21 * matrix2.M12) + (matrix1.M22 * matrix2.M22),
((matrix1.OffsetX * matrix2.M11) + (matrix1.OffsetY * matrix2.M21)) + matrix2.OffsetX,
((matrix1.OffsetX * matrix2.M12) + (matrix1.OffsetY * matrix2.M22)) + matrix2.OffsetY);
}
/// <summary>
/// Implements WPF's Matrix.HasInverse on Silverlight.
/// </summary>
/// <param name="matrix">Matrix to check for inverse.</param>
/// <returns>True if the Matrix has an inverse.</returns>
private static bool MatrixHasInverse(Matrix matrix)
{
// WPF equivalent of following code:
// return matrix.HasInverse;
return (0 != ((matrix.M11 * matrix.M22) - (matrix.M12 * matrix.M21)));
}
}
}
In the App.xaml file
Add namespace common
xmlns:common="using:Common"
create a new style inside of ApplicationResources
<Application.Resources>
<Style TargetType="common:LayoutTransformer">
<Setter Property="Foreground" Value="#FF000000"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="common:LayoutTransformer">
<Grid x:Name="TransformRoot" Background="{TemplateBinding Background}">
<ContentPresenter
x:Name="Presenter"
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
Now to rotate a textblock anticlockwise by 90 degrees
Add namespace common
xmlns:common="using:Common"
And use this code
<common:LayoutTransformer>
<common:LayoutTransformer.LayoutTransform>
<RotateTransform Angle="-90" />
</common:LayoutTransformer.LayoutTransform>
<TextBlock Text="CATEGORIES"
FontSize="30"/>
</common:LayoutTransformer>
If you rotate the Border (the parent), TextBlock will be rotated as well since it is the child of the Border.
<Border Height="80"
Background="Teal">
<Border.RenderTransform>
<RotateTransform Angle="-90" />
</Border.RenderTransform>
<TextBlock Text="CATEGORIES"
Foreground="White"
FontFamily="Segoe UI Black"
FontSize="30">
</TextBlock>
</Border>
I'm struggling to figure out how to wrap my listview items horizontally and fill up available space within my listview.
So far, the items within my list view do not wrap.
XAML:
<Grid Grid.Row="4" Grid.RowSpacing="3" Grid.ColumnSpacing="3" BackgroundColor="Silver">
<ListView ItemsSource="{Binding EmployeeIds}" SelectedItem="{Binding SelectedEmployeeId}"
BackgroundColor="Black" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<customcontrols:WrapLayoutOld Orientation="Horizontal">
<Label Text="{Binding Value}" TextColor="Yellow" XAlign="Start" />
</customcontrols:WrapLayoutOld>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
WrapLayout:
using System;
using System.Linq;
using System.Collections.Generic;
using Xamarin.Forms;
namespace Custom.Controls
{
/// <summary>
/// New WrapLayout
/// </summary>
/// <author>Jason Smith</author>
public class WrapLayout : Layout<View>
{
Dictionary<View, SizeRequest> layoutCache = new Dictionary<View, SizeRequest>();
/// <summary>
/// Backing Storage for the Spacing property
/// </summary>
public static readonly BindableProperty SpacingProperty =
BindableProperty.Create<WrapLayout, double>(w => w.Spacing, 5,
propertyChanged: (bindable, oldvalue, newvalue) => ((WrapLayout)bindable).layoutCache.Clear());
/// <summary>
/// Spacing added between elements (both directions)
/// </summary>
/// <value>The spacing.</value>
public double Spacing
{
get { return (double)GetValue(SpacingProperty); }
set { SetValue(SpacingProperty, value); }
}
public WrapLayout()
{
VerticalOptions = HorizontalOptions = LayoutOptions.FillAndExpand;
}
protected override void OnChildMeasureInvalidated()
{
base.OnChildMeasureInvalidated();
layoutCache.Clear();
}
protected override SizeRequest OnSizeRequest(double widthConstraint, double heightConstraint)
{
double lastX;
double lastY;
var layout = NaiveLayout(widthConstraint, heightConstraint, out lastX, out lastY);
return new SizeRequest(new Size(lastX, lastY));
}
protected override void LayoutChildren(double x, double y, double width, double height)
{
double lastX, lastY;
var layout = NaiveLayout(width, height, out lastX, out lastY);
foreach (var t in layout)
{
var offset = (int)((width - t.Last().Item2.Right) / 2);
foreach (var dingus in t)
{
var location = new Rectangle(dingus.Item2.X + x + offset, dingus.Item2.Y + y, dingus.Item2.Width, dingus.Item2.Height);
LayoutChildIntoBoundingRegion(dingus.Item1, location);
}
}
}
private List<List<Tuple<View, Rectangle>>> NaiveLayout(double width, double height, out double lastX, out double lastY)
{
double startX = 0;
double startY = 0;
double right = width;
double nextY = 0;
lastX = 0;
lastY = 0;
var result = new List<List<Tuple<View, Rectangle>>>();
var currentList = new List<Tuple<View, Rectangle>>();
foreach (var child in Children)
{
SizeRequest sizeRequest;
if (!layoutCache.TryGetValue(child, out sizeRequest))
{
layoutCache[child] = sizeRequest = child.GetSizeRequest(double.PositiveInfinity, double.PositiveInfinity);
}
var paddedWidth = sizeRequest.Request.Width + Spacing;
var paddedHeight = sizeRequest.Request.Height + Spacing;
if (startX + paddedWidth > right)
{
startX = 0;
startY += nextY;
if (currentList.Count > 0)
{
result.Add(currentList);
currentList = new List<Tuple<View, Rectangle>>();
}
}
currentList.Add(new Tuple<View, Rectangle>(child, new Rectangle(startX, startY, sizeRequest.Request.Width, sizeRequest.Request.Height)));
lastX = Math.Max(lastX, startX + paddedWidth);
lastY = Math.Max(lastY, startY + paddedHeight);
nextY = Math.Max(nextY, paddedHeight);
startX += paddedWidth;
}
result.Add(currentList);
return result;
}
}
/// <summary>
/// Simple Layout panel which performs wrapping on the boundaries.
/// </summary>
public class WrapLayoutOld : Layout<View>
{
/// <summary>
/// Backing Storage for the Orientation property
/// </summary>
public static readonly BindableProperty OrientationProperty =
BindableProperty.Create<WrapLayoutOld, StackOrientation>(w => w.Orientation, StackOrientation.Vertical,
propertyChanged: (bindable, oldvalue, newvalue) => ((WrapLayoutOld)bindable).OnSizeChanged());
/// <summary>
/// Orientation (Horizontal or Vertical)
/// </summary>
public StackOrientation Orientation
{
get { return (StackOrientation)GetValue(OrientationProperty); }
set { SetValue(OrientationProperty, value); }
}
/// <summary>
/// Backing Storage for the Spacing property
/// </summary>
public static readonly BindableProperty SpacingProperty =
BindableProperty.Create<WrapLayoutOld, double>(w => w.Spacing, 6,
propertyChanged: (bindable, oldvalue, newvalue) => ((WrapLayoutOld)bindable).OnSizeChanged());
/// <summary>
/// Spacing added between elements (both directions)
/// </summary>
/// <value>The spacing.</value>
public double Spacing
{
get { return (double)GetValue(SpacingProperty); }
set { SetValue(SpacingProperty, value); }
}
/// <summary>
/// This is called when the spacing or orientation properties are changed - it forces
/// the control to go back through a layout pass.
/// </summary>
private void OnSizeChanged()
{
this.ForceLayout();
}
//http://forums.xamarin.com/discussion/17961/stacklayout-with-horizontal-orientation-how-to-wrap-vertically#latest
// protected override void OnPropertyChanged
// (string propertyName = null)
// {
// base.OnPropertyChanged(propertyName);
// if ((propertyName == WrapLayout.OrientationProperty.PropertyName) ||
// (propertyName == WrapLayout.SpacingProperty.PropertyName)) {
// this.OnSizeChanged();
// }
// }
/// <summary>
/// This method is called during the measure pass of a layout cycle to get the desired size of an element.
/// </summary>
/// <param name="widthConstraint">The available width for the element to use.</param>
/// <param name="heightConstraint">The available height for the element to use.</param>
protected override SizeRequest OnSizeRequest(double widthConstraint, double heightConstraint)
{
if (WidthRequest > 0)
widthConstraint = Math.Min(widthConstraint, WidthRequest);
if (HeightRequest > 0)
heightConstraint = Math.Min(heightConstraint, HeightRequest);
double internalWidth = double.IsPositiveInfinity(widthConstraint) ? double.PositiveInfinity : Math.Max(0, widthConstraint);
double internalHeight = double.IsPositiveInfinity(heightConstraint) ? double.PositiveInfinity : Math.Max(0, heightConstraint);
return Orientation == StackOrientation.Vertical
? DoVerticalMeasure(internalWidth, internalHeight)
: DoHorizontalMeasure(internalWidth, internalHeight);
}
/// <summary>
/// Does the vertical measure.
/// </summary>
/// <returns>The vertical measure.</returns>
/// <param name="widthConstraint">Width constraint.</param>
/// <param name="heightConstraint">Height constraint.</param>
private SizeRequest DoVerticalMeasure(double widthConstraint, double heightConstraint)
{
int columnCount = 1;
double width = 0;
double height = 0;
double minWidth = 0;
double minHeight = 0;
double heightUsed = 0;
foreach (var item in Children)
{
var size = item.GetSizeRequest(widthConstraint, heightConstraint);
width = Math.Max(width, size.Request.Width);
var newHeight = height + size.Request.Height + Spacing;
if (newHeight > heightConstraint)
{
columnCount++;
heightUsed = Math.Max(height, heightUsed);
height = size.Request.Height;
}
else
height = newHeight;
minHeight = Math.Max(minHeight, size.Minimum.Height);
minWidth = Math.Max(minWidth, size.Minimum.Width);
}
if (columnCount > 1)
{
height = Math.Max(height, heightUsed);
width *= columnCount; // take max width
}
return new SizeRequest(new Size(width, height), new Size(minWidth, minHeight));
}
/// <summary>
/// Does the horizontal measure.
/// </summary>
/// <returns>The horizontal measure.</returns>
/// <param name="widthConstraint">Width constraint.</param>
/// <param name="heightConstraint">Height constraint.</param>
private SizeRequest DoHorizontalMeasure(double widthConstraint, double heightConstraint)
{
int rowCount = 1;
double width = 0;
double height = 0;
double minWidth = 0;
double minHeight = 0;
double widthUsed = 0;
foreach (var item in Children)
{
var size = item.GetSizeRequest(widthConstraint, heightConstraint);
height = Math.Max(height, size.Request.Height);
var newWidth = width + size.Request.Width + Spacing;
if (newWidth > widthConstraint)
{
rowCount++;
widthUsed = Math.Max(width, widthUsed);
width = size.Request.Width;
}
else
width = newWidth;
minHeight = Math.Max(minHeight, size.Minimum.Height);
minWidth = Math.Max(minWidth, size.Minimum.Width);
}
if (rowCount > 1)
{
width = Math.Max(width, widthUsed);
height = (height + Spacing) * rowCount - Spacing; // via MitchMilam
}
return new SizeRequest(new Size(width, height), new Size(minWidth, minHeight));
}
/// <summary>
/// Positions and sizes the children of a Layout.
/// </summary>
/// <param name="x">A value representing the x coordinate of the child region bounding box.</param>
/// <param name="y">A value representing the y coordinate of the child region bounding box.</param>
/// <param name="width">A value representing the width of the child region bounding box.</param>
/// <param name="height">A value representing the height of the child region bounding box.</param>
protected override void LayoutChildren(double x, double y, double width, double height)
{
if (Orientation == StackOrientation.Vertical)
{
double colWidth = 0;
double yPos = y, xPos = x;
foreach (var child in Children.Where(c => c.IsVisible))
{
var request = child.GetSizeRequest(width, height);
double childWidth = request.Request.Width;
double childHeight = request.Request.Height;
colWidth = Math.Max(colWidth, childWidth);
if (yPos + childHeight > height)
{
yPos = y;
xPos += colWidth + Spacing;
colWidth = 0;
}
var region = new Rectangle(xPos, yPos, childWidth, childHeight);
LayoutChildIntoBoundingRegion(child, region);
yPos += region.Height + Spacing;
}
}
else {
double rowHeight = 0;
double yPos = y, xPos = x;
foreach (var child in Children.Where(c => c.IsVisible))
{
var request = child.GetSizeRequest(width, height);
double childWidth = request.Request.Width;
double childHeight = request.Request.Height;
rowHeight = Math.Max(rowHeight, childHeight);
if (xPos + childWidth > width)
{
xPos = x;
yPos += rowHeight + Spacing;
rowHeight = 0;
}
var region = new Rectangle(xPos, yPos, childWidth, childHeight);
LayoutChildIntoBoundingRegion(child, region);
xPos += region.Width + Spacing;
}
}
}
}
}
FlexLayout has been introduced in Xamarin.Forms 3.0, so if you can upgrade you should definitely use it:
FlexLayout is similar to the Xamarin.Forms StackLayout in that it can
arrange its children horizontally and vertically in a stack. However,
the FlexLayout is also capable of wrapping its children if there are
too many to fit in a single row or column, and also has many options
for orientation, alignment, and adapting to various screen sizes.
Official docs.
I have this list of images and they wrap correctly using the same class you are using, it may be related to LayoutOptions:
WrapLayout container = new WrapLayout
{
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.StartAndExpand,
Orientation = StackOrientation.Horizontal,
Padding = 10,
Spacing = 10
};
Image thumbnail = new Image
{
HeightRequest = 80,
WidthRequest = 80,
HorizontalOptions = LayoutOptions.Start,
VerticalOptions = LayoutOptions.Start,
//BackgroundColor = Color.Black
Source = item.ImageText,
Aspect = Aspect.AspectFit
};
As you can see here http://allopensensors.com/profile/andreas/
the date on x-axis is nonreadable. I'd like to add a line break. How can i solve this?
AmCharts.ready(function () {
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.pathToImages = "http://allopensensors.com/amcharts/images/";
chart.dataProvider = chartData;
chart.marginLeft = 10;
chart.categoryField = "year";
chart.dataDateFormat = "YYYY-MM-DD JJ:NN:SS";
// listen for "dataUpdated" event (fired when chart is inited) and call zoomChart method when it happens
chart.addListener("dataUpdated", zoomChart);
// AXES
// category
var categoryAxis = chart.categoryAxis;
// categoryAxis.parseDates = true; // as our data is date-based, we set parseDates to true
categoryAxis.minPeriod = "200"; // our data is yearly, so we set minPeriod to YYYY
categoryAxis.dashLength = 3;
categoryAxis.minorGridEnabled = true;
categoryAxis.minorGridAlpha = 0.1;
// value
var valueAxis = new AmCharts.ValueAxis();
valueAxis.axisAlpha = 0;
valueAxis.inside = true;
valueAxis.dashLength = 3;
chart.addValueAxis(valueAxis);
// GRAPH
graph = new AmCharts.AmGraph();
graph.type = "smoothedLine"; // this line makes the graph smoothed line.
graph.lineColor = "#d1655d";
graph.negativeLineColor = "#637bb6"; // this line makes the graph to change color when it drops below 0
graph.bullet = "round";
graph.bulletSize = 8;
graph.bulletBorderColor = "#FFFFFF";
graph.bulletBorderAlpha = 1;
graph.bulletBorderThickness = 2;
graph.lineThickness = 2;
graph.valueField = "value";
graph.balloonText = "[[category]]<br><b><span style='font-size:14px;'>[[value]]</span></b>";
chart.addGraph(graph);
// CURSOR
var chartCursor = new AmCharts.ChartCursor();
chartCursor.cursorAlpha = 0;
chartCursor.cursorPosition = "mouse";
chartCursor.categoryBalloonDateFormat = "JJ:NN:SS";
chart.addChartCursor(chartCursor);
// SCROLLBAR
var chartScrollbar = new AmCharts.ChartScrollbar();
chart.addChartScrollbar(chartScrollbar);
chart.creditsPosition = "bottom-right";
// WRITE
chart.write("chartdiv");
});
// this method is called when chart is first inited as we listen for "dataUpdated" event
function zoomChart() {
// different zoom methods can be used - zoomToIndexes, zoomToDates, zoomToCategoryValues
// chart.zoomToDates(new Date(1972, 0), new Date(2200, 0));
chart.zoomToIndexes(chartData.length - 40, chartData.length - 1);
}
To make it readable, you can rotate the labels with custom angle. Try categoryAxis.labelRotation : 45
For Reference: http://www.amcharts.com/demos/column-with-rotated-series/
Hope it helps!
I need an algorithm that would take n rectangles of any sizes, and calculate a rectangle big enough to fit them all, minimizing its area so the wasted area is minimum, and also returning the position of all the smaller rectangles within.
The specific task I need this to implement on is in a sprite sheet compiler that would take individual PNG files and make a large PNG with all the images in it, so individual frames can be blitted from this surface at run time.
A nice to have feature would be that it aims to a specific given width/height ratio, but it's not mandatory.
I'd prefer simple, generic code I can port to another language.
This is what I put together for my own needs. The T parameter is whatever object you want associated with the results (think of it like the Tag property). It takes a list of sizes and returns a list of Rects that are arranged
static class LayoutHelper
{
/// <summary>
/// Determines the best fit of a List of Sizes, into the desired rectangle shape
/// </summary>
/// <typeparam name="T">Holder for an associated object (e.g., window, UserControl, etc.)</typeparam>
/// <param name="desiredWidthToHeightRatio">the target rectangle shape</param>
/// <param name="rectsToArrange">List of sizes that have to fit in the rectangle</param>
/// <param name="lossiness">1 = non-lossy (slow). Greater numbers improve speed, but miss some best fits</param>
/// <returns>list of arranged rects</returns>
static public List<Tuple<T, Rect>> BestFitRects<T>(double desiredWidthToHeightRatio,
List<Tuple<Size, T>> rectsToArrange, int lossiness = 10)
{
// helper anonymous function that tests for rectangle intersections or boundary violations
var CheckIfRectsIntersect = new Func<Rect, List<Rect>, double, bool>((one, list, containerHeight) =>
{
if (one.Y + one.Height > containerHeight) return true;
return list.Any(two =>
{
if ((one.Top > two.Bottom) ||
(one.Bottom < two.Top) ||
(one.Left > two.Right) ||
(one.Right < two.Left)) return false; // no intersection
return true; // intersection found
});
});
// helper anonymous function for adding drop points
var AddNewPotentialDropPoints = new Action<SortedDictionary<Point, object>, Rect>(
(potentialDropPoints, newRect) =>
{
// Only two locations make sense for placing a new rectangle, underneath the
// bottom left corner or to the right of a top right corner
potentialDropPoints[new Point(newRect.X + newRect.Width + 1,
newRect.Y)] = null;
potentialDropPoints[new Point(newRect.X,
newRect.Y + newRect.Height + 1)] = null;
});
var sync = new object();
// the outer boundary that limits how high the rectangles can stack vertically
var containingRectHeight = Convert.ToInt32(rectsToArrange.Max(a => a.Item1.Height));
// always try packing using the tallest rectangle first, working down in height
var largestToSmallest = rectsToArrange.OrderByDescending(a => a.Item1.Height).ToList();
// find the maximum possible container height needed
var totalHeight = Convert.ToInt32(rectsToArrange.Sum(a => a.Item1.Height));
List<Tuple<T, Rect>> bestResults = null;
// used to find the best packing arrangement that approximates the target container dimensions ratio
var bestResultsProximityToDesiredRatio = double.MaxValue;
// try all arrangements for all suitable container sizes
Parallel.For(0, ((totalHeight + 1) - containingRectHeight) / lossiness,
//new ParallelOptions() { MaxDegreeOfParallelism = 1},
currentHeight =>
{
var potentialDropPoints = new SortedDictionary<Point, object>(Comparer<Point>.Create((p1, p2) =>
{
// choose the leftmost, then highest point as earlier in the sort order
if (p1.X != p2.X) return p1.X.CompareTo(p2.X);
return p1.Y.CompareTo(p2.Y);
}));
var localResults = new List<Tuple<T, Rect>>();
// iterate through the rectangles from largest to smallest
largestToSmallest.ForEach(currentSize =>
{
// check to see if the next rectangle fits in with the currently arranged rectangles
if (!potentialDropPoints.Any(dropPoint =>
{
var workingPoint = dropPoint.Key;
Rect? lastFittingRect = null;
var lowY = workingPoint.Y;
var highY = workingPoint.Y - 1;
var boundaryFound = false;
// check if it fits in the current arrangement of rects
do
{
// create a positioned rectangle out of the size dimensions
var workingRect = new Rect(workingPoint,
new Point(workingPoint.X + currentSize.Item1.Width,
workingPoint.Y + currentSize.Item1.Height));
// keep moving it up in binary search fashion until it bumps the higher rect
if (!CheckIfRectsIntersect(workingRect, localResults.Select(a => a.Item2).ToList(),
containingRectHeight + (currentHeight * lossiness)))
{
lastFittingRect = workingRect;
if (!boundaryFound)
{
highY = Math.Max(lowY - ((lowY - highY) * 2), 0);
if (highY == 0) boundaryFound = true;
}
else
{
lowY = workingPoint.Y;
}
}
else
{
boundaryFound = true;
highY = workingPoint.Y;
}
workingPoint = new Point(workingPoint.X, lowY - (lowY - highY) / 2);
} while (lowY - highY > 1);
if (lastFittingRect.HasValue) // found the sweet spot for this rect
{
var newRect = lastFittingRect.Value;
potentialDropPoints.Remove(dropPoint.Key);
// successfully found the best location for the new rectangle, so add it to the pending results
localResults.Add(Tuple.Create(currentSize.Item2, newRect));
AddNewPotentialDropPoints(potentialDropPoints, newRect);
return true;
}
return false;
}))
{
// this only occurs on the first square
var newRect = new Rect(0, 0, currentSize.Item1.Width, currentSize.Item1.Height);
localResults.Add(Tuple.Create(currentSize.Item2, newRect));
AddNewPotentialDropPoints(potentialDropPoints, newRect);
}
});
// layout is complete, now see if this layout is the best one found so far
var layoutHeight = localResults.Max(a => a.Item2.Y + a.Item2.Height);
var layoutWidth = localResults.Max(a => a.Item2.X + a.Item2.Width);
var widthMatchingDesiredRatio = desiredWidthToHeightRatio * layoutHeight;
double ratioProximity;
if (layoutWidth < widthMatchingDesiredRatio)
ratioProximity = widthMatchingDesiredRatio / layoutWidth;
else
ratioProximity = layoutWidth / widthMatchingDesiredRatio;
lock (sync)
{
if (ratioProximity < bestResultsProximityToDesiredRatio)
{
// this layout is the best approximation of the desired container dimensions, so far
bestResults = localResults;
bestResultsProximityToDesiredRatio = ratioProximity;
}
}
});
return bestResults ?? new List<Tuple<T, Rect>>() {Tuple.Create(rectsToArrange[0].Item2,
new Rect(new Point(0, 0), new Point(rectsToArrange[0].Item1.Width, rectsToArrange[0].Item1.Height))) };
}
}
Has anyone ever had any luck figuring out how to add a comment to Excel using the Open XML SDK 2.0? I couldn't find any documentation on where to get started on this issue.
The below code will take the worksheet that you want to add comments to and then iterate over the commentsToAdd dictionary. The dictionary key is the cell reference (ie. A1) and the value is the comment text to be added.
/// <summary>
/// Adds all the comments defined in the commentsToAddDict dictionary to the worksheet
/// </summary>
/// <param name="worksheetPart">Worksheet Part</param>
/// <param name="commentsToAddDict">Dictionary of cell references as the key (ie. A1) and the comment text as the value</param>
public static void InsertComments(WorksheetPart worksheetPart, Dictionary<string, string> commentsToAddDict)
{
if (commentsToAddDict.Any())
{
string commentsVmlXml = string.Empty;
// Create all the comment VML Shape XML
foreach (var commentToAdd in commentsToAddDict)
{
commentsVmlXml += GetCommentVMLShapeXML(GetColumnName(commentToAdd.Key), GetRowIndex(commentToAdd.Key).ToString());
}
// The VMLDrawingPart should contain all the definitions for how to draw every comment shape for the worksheet
VmlDrawingPart vmlDrawingPart = worksheetPart.AddNewPart<VmlDrawingPart>();
using (XmlTextWriter writer = new XmlTextWriter(vmlDrawingPart.GetStream(FileMode.Create), Encoding.UTF8))
{
writer.WriteRaw("<xml xmlns:v=\"urn:schemas-microsoft-com:vml\"\r\n xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n xmlns:x=\"urn:schemas-microsoft-com:office:excel\">\r\n <o:shapelayout v:ext=\"edit\">\r\n <o:idmap v:ext=\"edit\" data=\"1\"/>\r\n" +
"</o:shapelayout><v:shapetype id=\"_x0000_t202\" coordsize=\"21600,21600\" o:spt=\"202\"\r\n path=\"m,l,21600r21600,l21600,xe\">\r\n <v:stroke joinstyle=\"miter\"/>\r\n <v:path gradientshapeok=\"t\" o:connecttype=\"rect\"/>\r\n </v:shapetype>"
+ commentsVmlXml + "</xml>");
}
// Create the comment elements
foreach (var commentToAdd in commentsToAddDict)
{
WorksheetCommentsPart worksheetCommentsPart = worksheetPart.WorksheetCommentsPart ?? worksheetPart.AddNewPart<WorksheetCommentsPart>();
// We only want one legacy drawing element per worksheet for comments
if (worksheetPart.Worksheet.Descendants<LegacyDrawing>().SingleOrDefault() == null)
{
string vmlPartId = worksheetPart.GetIdOfPart(vmlDrawingPart);
LegacyDrawing legacyDrawing = new LegacyDrawing() { Id = vmlPartId };
worksheetPart.Worksheet.Append(legacyDrawing);
}
Comments comments;
bool appendComments = false;
if (worksheetPart.WorksheetCommentsPart.Comments != null)
{
comments = worksheetPart.WorksheetCommentsPart.Comments;
}
else
{
comments = new Comments();
appendComments = true;
}
// We only want one Author element per Comments element
if (worksheetPart.WorksheetCommentsPart.Comments == null)
{
Authors authors = new Authors();
Author author = new Author();
author.Text = "Author Name";
authors.Append(author);
comments.Append(authors);
}
CommentList commentList;
bool appendCommentList = false;
if (worksheetPart.WorksheetCommentsPart.Comments != null &&
worksheetPart.WorksheetCommentsPart.Comments.Descendants<CommentList>().SingleOrDefault() != null)
{
commentList = worksheetPart.WorksheetCommentsPart.Comments.Descendants<CommentList>().Single();
}
else
{
commentList = new CommentList();
appendCommentList = true;
}
Comment comment = new Comment() { Reference = commentToAdd.Key, AuthorId = (UInt32Value)0U };
CommentText commentTextElement = new CommentText();
Run run = new Run();
RunProperties runProperties = new RunProperties();
Bold bold = new Bold();
FontSize fontSize = new FontSize() { Val = 8D };
Color color = new Color() { Indexed = (UInt32Value)81U };
RunFont runFont = new RunFont() { Val = "Tahoma" };
RunPropertyCharSet runPropertyCharSet = new RunPropertyCharSet() { Val = 1 };
runProperties.Append(bold);
runProperties.Append(fontSize);
runProperties.Append(color);
runProperties.Append(runFont);
runProperties.Append(runPropertyCharSet);
Text text = new Text();
text.Text = commentToAdd.Value;
run.Append(runProperties);
run.Append(text);
commentTextElement.Append(run);
comment.Append(commentTextElement);
commentList.Append(comment);
// Only append the Comment List if this is the first time adding a comment
if (appendCommentList)
{
comments.Append(commentList);
}
// Only append the Comments if this is the first time adding Comments
if (appendComments)
{
worksheetCommentsPart.Comments = comments;
}
}
}
}
Helper method that will create the VML XML for the Shape:
/// <summary>
/// Creates the VML Shape XML for a comment. It determines the positioning of the
/// comment in the excel document based on the column name and row index.
/// </summary>
/// <param name="columnName">Column name containing the comment</param>
/// <param name="rowIndex">Row index containing the comment</param>
/// <returns>VML Shape XML for a comment</returns>
private static string GetCommentVMLShapeXML(string columnName, string rowIndex)
{
string commentVmlXml = string.Empty;
// Parse the row index into an int so we can subtract one
int commentRowIndex;
if (int.TryParse(rowIndex, out commentRowIndex))
{
commentRowIndex -= 1;
commentVmlXml = "<v:shape id=\"" + Guid.NewGuid().ToString().Replace("-", "") + "\" type=\"#_x0000_t202\" style=\'position:absolute;\r\n margin-left:59.25pt;margin-top:1.5pt;width:96pt;height:55.5pt;z-index:1;\r\n visibility:hidden\' fillcolor=\"#ffffe1\" o:insetmode=\"auto\">\r\n <v:fill color2=\"#ffffe1\"/>\r\n" +
"<v:shadow on=\"t\" color=\"black\" obscured=\"t\"/>\r\n <v:path o:connecttype=\"none\"/>\r\n <v:textbox style=\'mso-fit-shape-to-text:true'>\r\n <div style=\'text-align:left\'></div>\r\n </v:textbox>\r\n <x:ClientData ObjectType=\"Note\">\r\n <x:MoveWithCells/>\r\n" +
"<x:SizeWithCells/>\r\n <x:Anchor>\r\n" + GetAnchorCoordinatesForVMLCommentShape(columnName, rowIndex) + "</x:Anchor>\r\n <x:AutoFill>False</x:AutoFill>\r\n <x:Row>" + commentRowIndex + "</x:Row>\r\n <x:Column>" + GetColumnIndexFromName(columnName) + "</x:Column>\r\n </x:ClientData>\r\n </v:shape>";
}
return commentVmlXml;
}
Helpers to figure out the Column Index and coordinates for the comment Shape:
/// <summary>
/// Gets the coordinates for where on the excel spreadsheet to display the VML comment shape
/// </summary>
/// <param name="columnName">Column name of where the comment is located (ie. B)</param>
/// <param name="rowIndex">Row index of where the comment is located (ie. 2)</param>
/// <returns><see cref="<x:Anchor>"/> coordinates in the form of a comma separated list</returns>
private static string GetAnchorCoordinatesForVMLCommentShape(string columnName, string rowIndex)
{
string coordinates = string.Empty;
int startingRow = 0;
int startingColumn = GetColumnIndexFromName(columnName).Value;
// From (upper right coordinate of a rectangle)
// [0] Left column
// [1] Left column offset
// [2] Left row
// [3] Left row offset
// To (bottom right coordinate of a rectangle)
// [4] Right column
// [5] Right column offset
// [6] Right row
// [7] Right row offset
List<int> coordList = new List<int>(8) { 0, 0, 0, 0, 0, 0, 0, 0};
if (int.TryParse(rowIndex, out startingRow))
{
// Make the row be a zero based index
startingRow -= 1;
coordList[0] = startingColumn + 1; // If starting column is A, display shape in column B
coordList[1] = 15;
coordList[2] = startingRow;
coordList[4] = startingColumn + 3; // If starting column is A, display shape till column D
coordList[5] = 15;
coordList[6] = startingRow + 3; // If starting row is 0, display 3 rows down to row 3
// The row offsets change if the shape is defined in the first row
if (startingRow == 0)
{
coordList[3] = 2;
coordList[7] = 16;
}
else
{
coordList[3] = 10;
coordList[7] = 4;
}
coordinates = string.Join(",", coordList.ConvertAll<string>(x => x.ToString()).ToArray());
}
return coordinates;
}
/// <summary>
/// Given just the column name (no row index), it will return the zero based column index.
/// Note: This method will only handle columns with a length of up to two (ie. A to Z and AA to ZZ).
/// A length of three can be implemented when needed.
/// </summary>
/// <param name="columnName">Column Name (ie. A or AB)</param>
/// <returns>Zero based index if the conversion was successful; otherwise null</returns>
public static int? GetColumnIndexFromName(string columnName)
{
int? columnIndex = null;
string[] colLetters = Regex.Split(columnName, "([A-Z]+)");
colLetters = colLetters.Where(s => !string.IsNullOrEmpty(s)).ToArray();
if (colLetters.Count() <= 2)
{
int index = 0;
foreach (string col in colLetters)
{
List<char> col1 = colLetters.ElementAt(index).ToCharArray().ToList();
int? indexValue = Letters.IndexOf(col1.ElementAt(index));
if (indexValue != -1)
{
// The first letter of a two digit column needs some extra calculations
if (index == 0 && colLetters.Count() == 2)
{
columnIndex = columnIndex == null ? (indexValue + 1) * 26 : columnIndex + ((indexValue + 1) * 26);
}
else
{
columnIndex = columnIndex == null ? indexValue : columnIndex + indexValue;
}
}
index++;
}
}
return columnIndex;
}
Don't forget to save your worksheet and workbook once you are done in order to see the changes.
Many people ask "how to do this" / "how to do that" using OpenXML.
The most frequent answer say that OpenXML is painful to work with (I agree) refer to 3-rd party library (specifically ClosedXML).
If you are not using a 3-rd party library then I would like to answer with a general tip based on this thread: http://social.msdn.microsoft.com/Forums/office/en-US/81f767d0-15ac-42fe-b122-6c5c02b6c373/cell-color-and-add-comment?forum=oxmlsdk
You can create a empty workbook named "Unchanged.xlsx", then do the customization which you want to reflect to C# code in Open XML SaveAs the changed workbook named as "Changed.xlsx". Now open the Open XML SDK tool, use compare files feature, you then can see the changes made to the workbook and how can they been done with Open XML SDK via C#.
There is an option reflect code that gives you a lot of hints about what is going on, see (incomplete) example below:
As it is autogenerated code it can be simplified / inlined / reduced. After a week or two you'll get into speed.