Create custom Shape Control in UWP (Universal Windows Apps), Windows 10 - c#

I want to create a custom Shape control, that paints different shapes like Polygon, Ellipse, Rectangle, etc, depending on some custom properties.
I was able to create a custom template control ColorShape like this:
<Style TargetType="local:CustomShape">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:CustomShape">
<ContentControl x:Name="shapeParent">
</ContentControl>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
And then, override the OnTemplateChanged method, and insert a corresponding Shape control inside the shapeParent ContentControl
But what I'd like is to actually extend the Shape, so I can treat all the shapes, framewok and custom, in the same way.
In WPF we were able to extend the Shape and override the property DefiningGeometry.
In UWP it doesn´t exist any DefiningGeometry property to override.
How is it possible to create a custom Shape control and define the corresponding Geometry?

The only way I found to create custom shapes in UWP is to extend the Path class and set its Data property.
Updating the Data property to account for changes in other dependency properties (like Width) must not be done in layouting relevant sections, like the LayoutUpdated event or the ArrangeOverride method.
Setting Data leads to another layout run, so setting it in anything that is called during that would lead to an exception:
Layout cycle detected. Layout could not complete
The way I use is to register handler for property changed events and update Data in them.
I have written a blog post that explains it in a bit more detail.
This is the example I used:
public class CandlestickShape : Path
{
public double StartValue
{
get { return Convert.ToDouble(GetValue(StartValueProperty)); }
set { SetValue(StartValueProperty, value); }
}
public static readonly DependencyProperty StartValueProperty =
DependencyProperty.Register("StartValue", typeof(double), typeof(CandlestickShape), new PropertyMetadata(0));
public double EndValue
{
get { return Convert.ToDouble(GetValue(EndValueProperty)); }
set { SetValue(EndValueProperty, value); }
}
public static readonly DependencyProperty EndValueProperty =
DependencyProperty.Register("EndValue", typeof(double), typeof(CandlestickShape), new PropertyMetadata(0));
public double MinValue
{
get { return Convert.ToDouble(GetValue(MinValueProperty)); }
set { SetValue(MinValueProperty, value); }
}
public static readonly DependencyProperty MinValueProperty =
DependencyProperty.Register("MinValue", typeof(double), typeof(CandlestickShape), new PropertyMetadata(0));
public double MaxValue
{
get { return Convert.ToDouble(GetValue(MaxValueProperty)); }
set { SetValue(MaxValueProperty, value); }
}
public static readonly DependencyProperty MaxValueProperty =
DependencyProperty.Register("MaxValue", typeof(double), typeof(CandlestickShape), new PropertyMetadata(0));
/// <summary>
/// Defines how many Pixel should be drawn for one Point
/// </summary>
public double PixelPerPoint
{
get { return Convert.ToDouble(GetValue(PointsPerPixelProperty)); }
set { SetValue(PointsPerPixelProperty, value); }
}
public static readonly DependencyProperty PointsPerPixelProperty =
DependencyProperty.Register("PixelPerPoint", typeof(double), typeof(CandlestickShape), new PropertyMetadata(0));
public CandlestickShape()
{
this.RegisterPropertyChangedCallback(CandlestickShape.WidthProperty, new DependencyPropertyChangedCallback(RenderAffectingPropertyChanged));
this.RegisterPropertyChangedCallback(CandlestickShape.StartValueProperty, new DependencyPropertyChangedCallback(RenderAffectingPropertyChanged));
this.RegisterPropertyChangedCallback(CandlestickShape.EndValueProperty, new DependencyPropertyChangedCallback(RenderAffectingPropertyChanged));
this.RegisterPropertyChangedCallback(CandlestickShape.MinValueProperty, new DependencyPropertyChangedCallback(RenderAffectingPropertyChanged));
this.RegisterPropertyChangedCallback(CandlestickShape.MaxValueProperty, new DependencyPropertyChangedCallback(RenderAffectingPropertyChanged));
this.RegisterPropertyChangedCallback(CandlestickShape.PointsPerPixelProperty, new DependencyPropertyChangedCallback(RenderAffectingPropertyChanged));
}
private void RenderAffectingPropertyChanged(DependencyObject o, DependencyProperty e)
{
(o as CandlestickShape)?.SetRenderData();
}
private void SetRenderData()
{
var maxBorderValue = Math.Max(this.StartValue, this.EndValue);
var minBorderValue = Math.Min(this.StartValue, this.EndValue);
double topLineLength = (this.MaxValue - maxBorderValue) * this.PixelPerPoint;
double bottomLineLength = (minBorderValue - this.MinValue) * this.PixelPerPoint;
double bodyLength = (this.EndValue - this.StartValue) * this.PixelPerPoint;
var fillColor = new SolidColorBrush(Colors.Green);
if (bodyLength < 0)
fillColor = new SolidColorBrush(Colors.Red);
bodyLength = Math.Abs(bodyLength);
var bodyGeometry = new RectangleGeometry
{
Rect = new Rect(new Point(0, topLineLength), new Point(this.Width, topLineLength + bodyLength)),
};
var topLineGeometry = new LineGeometry
{
StartPoint = new Point(this.Width / 2, 0),
EndPoint = new Point(this.Width / 2, topLineLength)
};
var bottomLineGeometry = new LineGeometry
{
StartPoint = new Point(this.Width / 2, topLineLength + bodyLength),
EndPoint = new Point(this.Width / 2, topLineLength + bodyLength + bottomLineLength)
};
this.Data = new GeometryGroup
{
Children = new GeometryCollection
{
bodyGeometry,
topLineGeometry,
bottomLineGeometry
}
};
this.Fill = fillColor;
this.Stroke = new SolidColorBrush(Colors.Black);
}
protected override Size ArrangeOverride(Size finalSize)
{
double height = (MaxValue - MinValue) * PixelPerPoint;
return new Size(this.Width, height);
}
protected override Size MeasureOverride(Size availableSize)
{
double height = (MaxValue - MinValue) * PixelPerPoint;
return new Size(this.Width, height);
}
}

Related

WPF Countdown user control issue

I am trying to use the final revision of this control from Stackexchange here:
https://codereview.stackexchange.com/questions/197197/countdown-control-with-arc-animation
When I use the code it counts down just a single second and finishes. I am not sure what issue is.
Hopefully someone can help out - thanks.
The code I am using is this:
Arc.cs
public class Arc : Shape
{
public Point Center
{
get => (Point)GetValue(CenterProperty);
set => SetValue(CenterProperty, value);
}
public static readonly DependencyProperty CenterProperty =
DependencyProperty.Register(nameof(Center), typeof(Point), typeof(Arc),
new FrameworkPropertyMetadata(new Point(), FrameworkPropertyMetadataOptions.AffectsRender));
public double StartAngle
{
get => (double)GetValue(StartAngleProperty);
set => SetValue(StartAngleProperty, value);
}
public static readonly DependencyProperty StartAngleProperty =
DependencyProperty.Register(nameof(StartAngle), typeof(double), typeof(Arc),
new FrameworkPropertyMetadata(0.0, FrameworkPropertyMetadataOptions.AffectsRender));
public double EndAngle
{
get => (double)GetValue(EndAngleProperty);
set => SetValue(EndAngleProperty, value);
}
public static readonly DependencyProperty EndAngleProperty =
DependencyProperty.Register(nameof(EndAngle), typeof(double), typeof(Arc),
new FrameworkPropertyMetadata(90.0, FrameworkPropertyMetadataOptions.AffectsRender));
public double Radius
{
get => (double)GetValue(RadiusProperty);
set => SetValue(RadiusProperty, value);
}
public static readonly DependencyProperty RadiusProperty =
DependencyProperty.Register(nameof(Radius), typeof(double), typeof(Arc),
new FrameworkPropertyMetadata(10.0, FrameworkPropertyMetadataOptions.AffectsRender));
public bool SmallAngle
{
get => (bool)GetValue(SmallAngleProperty);
set => SetValue(SmallAngleProperty, value);
}
public static readonly DependencyProperty SmallAngleProperty =
DependencyProperty.Register(nameof(SmallAngle), typeof(bool), typeof(Arc),
new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender));
static Arc() => DefaultStyleKeyProperty.OverrideMetadata(typeof(Arc), new FrameworkPropertyMetadata(typeof(Arc)));
protected override Geometry DefiningGeometry
{
get
{
double startAngleRadians = StartAngle * Math.PI / 180;
double endAngleRadians = EndAngle * Math.PI / 180;
double a0 = StartAngle < 0 ? startAngleRadians + 2 * Math.PI : startAngleRadians;
double a1 = EndAngle < 0 ? endAngleRadians + 2 * Math.PI : endAngleRadians;
if (a1 < a0)
a1 += Math.PI * 2;
SweepDirection d = SweepDirection.Counterclockwise;
bool large;
if (SmallAngle)
{
large = false;
d = (a1 - a0) > Math.PI ? SweepDirection.Counterclockwise : SweepDirection.Clockwise;
}
else
large = (Math.Abs(a1 - a0) < Math.PI);
Point p0 = Center + new Vector(Math.Cos(a0), Math.Sin(a0)) * Radius;
Point p1 = Center + new Vector(Math.Cos(a1), Math.Sin(a1)) * Radius;
List<PathSegment> segments = new List<PathSegment>
{
new ArcSegment(p1, new Size(Radius, Radius), 0.0, large, d, true)
};
List<PathFigure> figures = new List<PathFigure>
{
new PathFigure(p0, segments, true)
{
IsClosed = false
}
};
return new PathGeometry(figures, FillRule.EvenOdd, null);
}
}
}
Countdown.xaml
<UserControl x:Class="WpfApp.Countdown"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="450" Loaded="Countdown_Loaded">
<Viewbox>
<Grid Width="100" Height="100">
<Border Background="#222" Margin="5" CornerRadius="50">
<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
<Label Foreground="#fff" Content="{Binding SecondsRemaining}" FontSize="50" Margin="0, -10, 0, 0" />
<Label Foreground="#fff" Content="sec" HorizontalAlignment="Center" Margin="0, -15, 0, 0" />
</StackPanel>
</Border>
<uc:Arc
x:Name="Arc"
Center="50, 50"
StartAngle="-90"
EndAngle="-90"
Stroke="#45d3be"
StrokeThickness="5"
Radius="45" />
</Grid>
</Viewbox>
</UserControl>
Countdown.xaml.cs
public partial class Countdown : UserControl
{
public Duration Duration
{
get => (Duration)GetValue(DurationProperty);
set => SetValue(DurationProperty, value);
}
public static readonly DependencyProperty DurationProperty =
DependencyProperty.Register(nameof(Duration), typeof(Duration), typeof(Countdown), new PropertyMetadata(new Duration()));
public int SecondsRemaining
{
get => (int)GetValue(SecondsRemainingProperty);
set => SetValue(SecondsRemainingProperty, value);
}
public static readonly DependencyProperty SecondsRemainingProperty =
DependencyProperty.Register(nameof(SecondsRemaining), typeof(int), typeof(Countdown), new PropertyMetadata(0));
public event EventHandler Elapsed;
private readonly Storyboard _storyboard = new Storyboard();
public Countdown()
{
InitializeComponent();
DoubleAnimation animation = new DoubleAnimation(-90, 270, Duration);
Storyboard.SetTarget(animation, Arc);
Storyboard.SetTargetProperty(animation, new PropertyPath(nameof(Arc.EndAngle)));
_storyboard.Children.Add(animation);
DataContext = this;
}
private void Countdown_Loaded(object sender, EventArgs e)
{
if (IsVisible)
Start();
}
public void Start()
{
Stop();
_storyboard.CurrentTimeInvalidated += Storyboard_CurrentTimeInvalidated;
_storyboard.Completed += Storyboard_Completed;
_storyboard.Begin();
}
public void Stop()
{
_storyboard.CurrentTimeInvalidated -= Storyboard_CurrentTimeInvalidated;
_storyboard.Completed -= Storyboard_Completed;
_storyboard.Stop();
}
private void Storyboard_CurrentTimeInvalidated(object sender, EventArgs e)
{
ClockGroup cg = (ClockGroup)sender;
if (cg.CurrentTime == null) return;
TimeSpan elapsedTime = cg.CurrentTime.Value;
SecondsRemaining = (int)Math.Ceiling((Duration.TimeSpan - elapsedTime).TotalSeconds);
}
private void Storyboard_Completed(object sender, EventArgs e)
{
if (IsVisible)
Elapsed?.Invoke(this, EventArgs.Empty);
}
}
Your control is not properly initialized. You are currently not handling the property changes of the Duration property.
The dependency property values are applied after the control is instantiated (the constructor has returned): the XAML engine creates the element instance and then assigns the resources (e.g. a Style) and local values.
Therefore, your control will currently configure the animation (in the constructor) using the property's default Duration value (which is Duration.Automatic).
Generally, you must always assume that control properties are changing, e.g., via data binding or animation. To handle this scenarios you must register a dependency property changed callback - at least for every public property that has a direct impact on the behavior of the control.
SecondsRemaining should be a read-only dependency property.
You should use a TextBlock instead of a Label to display text.
To fix your issue, you must register a property changed callback for the Duration property to update the DoubleAnimation that depends on the value. Then store the actual DoubleAnimation in a private property, so that you can change its Duration on property changes:
public partial class Countdown : UserControl
{
public Duration Duration
{
get => (Duration)GetValue(DurationProperty);
set => SetValue(DurationProperty, value);
}
// Register the property changed callback
public static readonly DependencyProperty DurationProperty = DependencyProperty.Register(
nameof(Duration),
typeof(Duration),
typeof(Countdown),
new PropertyMetadata(new Duration(), OnDurationChanged));
// Store the DoubleAnimation in order to modify the Duration on property changes
private Timeline Timeline { get; set; }
public Countdown()
{
InitializeComponent();
// Store the DoubleAnimation in order to modify the Duration on property changes
this.Timeline = new DoubleAnimation(-90, 270, Duration);
Storyboard.SetTarget(this.Timeline, this.Arc);
Storyboard.SetTargetProperty(this.Timeline, new PropertyPath(nameof(Arc.EndAngle)));
_storyboard.Children.Add(this.Timeline);
DataContext = this;
}
// Handle the Duration property changes
private static void OnDurationChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var this_ = d as Countdown;
this_.Timeline.Duration = (Duration)e.NewValue;
}
}

How to animate a custom shape object in c# WPF

I am relatively new to c# and WPF, maybe that’s why I cannot find the (probably very obvious) answer to my problem. I have been trying and googling but with no success.
I have a custom shape class that returns 3 RectangleGeometries in a GeometryGroup. The 3 corresponding rectangles can be displayed in a Canvas in MainWindow as expected. I would now like to animate each of the rectangles individually, say drop the first one to the bottom of the canvas, rotate the second one and animate the width of the third one.
My own research says the key are Dependency Properties. So I registered them but I couldn’t get them to do any changes on the rectangles.
Preferably, I would do all this in code behind. Only the Canvas
has been added in XAML. Can it be done? Here is some code to work with.
Thank you in advance
using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;
namespace Test1
{
public partial class MainWindow : Window
{
CustomShape customShape = new CustomShape();
public MainWindow()
{
InitializeComponent();
customShape.Fill = Brushes.Blue;
cnvMain.Children.Add(customShape);
}
}
class CustomShape : Shape
{
private Rect rect1, rect2, rect3;
private RectangleGeometry rg1, rg2, rg3;
private GeometryGroup allRectangleGeometries = new GeometryGroup();
//Constructor
public CustomShape()
{
makeCustomShape();
}
private void makeCustomShape()
{
rect1 = new Rect(50, 20, 100, 50);
rg1 = new RectangleGeometry(rect1);
allRectangleGeometries.Children.Add(rg1);
rect2 = new Rect(200, 20, 60, 20);
rg2 = new RectangleGeometry(rect2);
allRectangleGeometries.Children.Add(rg2);
rect3 = new Rect(300, 20, 200, 80);
rg3 = new RectangleGeometry(rect3);
allRectangleGeometries.Children.Add(rg3);
}
protected override Geometry DefiningGeometry
{
get
{
return allRectangleGeometries;
}
}
}
}
Looks like I found an answer myself.
I implemented 3 Dependency Properties and a Callback method that is executed every time a property changes.
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace Test1
{
public partial class MainWindow : Window
{
CustomShape customShape = new CustomShape();
public MainWindow()
{
InitializeComponent();
customShape.Fill = Brushes.Blue;
cnvMain.Children.Add(customShape);
}
private void ButtonAnimate_Clicked(object sender, RoutedEventArgs e)
{
DoubleAnimation rec1Animation = new DoubleAnimation(500, TimeSpan.FromSeconds(1));
customShape.BeginAnimation(CustomShape.Rec1YProperty, rec1Animation);
DoubleAnimation rec2Animation = new DoubleAnimation(360, TimeSpan.FromSeconds(1));
customShape.BeginAnimation(CustomShape.Rec2RotateProperty, rec2Animation);
DoubleAnimation rec3Animation = new DoubleAnimation(400, TimeSpan.FromSeconds(1));
customShape.BeginAnimation(CustomShape.Rec3WidthProperty, rec3Animation);
}
}
class CustomShape : Shape
{
private Rect rect1, rect2, rect3;
private RectangleGeometry rg1, rg2, rg3;
private GeometryGroup allRectangleGeometries = new GeometryGroup();
public double Rec1Y
{
get { return (double)GetValue(Rec1YProperty); }
set { SetValue(Rec1YProperty, value); }
}
public static readonly DependencyProperty Rec1YProperty =
DependencyProperty.Register("Rec1Y", typeof(double), typeof(CustomShape), new PropertyMetadata(20d, new PropertyChangedCallback(OnAnyPropertyChanged)));
public double Rec2Rotate
{
get { return (double)GetValue(Rec2RotateProperty); }
set { SetValue(Rec2RotateProperty, value); }
}
public static readonly DependencyProperty Rec2RotateProperty =
DependencyProperty.Register("Rec2Rotate", typeof(double), typeof(CustomShape), new PropertyMetadata(0d, new PropertyChangedCallback(OnAnyPropertyChanged)));
public double Rec3Width
{
get { return (double)GetValue(Rec3WidthProperty); }
set { SetValue(Rec3WidthProperty, value); }
}
public static readonly DependencyProperty Rec3WidthProperty =
DependencyProperty.Register("Rec3Width", typeof(double), typeof(CustomShape), new PropertyMetadata(200d, new PropertyChangedCallback(OnAnyPropertyChanged)));
//Constructor
public CustomShape()
{
makeCustomShape();
}
private void makeCustomShape()
{
rect1 = new Rect(50, Rec1Y, 100, 50);
rg1 = new RectangleGeometry(rect1);
allRectangleGeometries.Children.Add(rg1);
rect2 = new Rect(200, 20, 60, 20);
rg2 = new RectangleGeometry(rect2);
rg2.Transform = new RotateTransform(Rec2Rotate, 230, 30);
allRectangleGeometries.Children.Add(rg2);
rect3 = new Rect(300, 20, Rec3Width, 80);
rg3 = new RectangleGeometry(rect3);
allRectangleGeometries.Children.Add(rg3);
}
private static void OnAnyPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
CustomShape customShape = source as CustomShape;
customShape.allRectangleGeometries.Children.Clear();
customShape.makeCustomShape();
}
protected override Geometry DefiningGeometry
{
get
{
return allRectangleGeometries;
}
}
}
}

Change attached property from CustomPanel doesn't refresh panel

I created dummy custom panel ShelfPanel with attached property Exact influence panel arrange:
class ShelfPanel : Panel
{
#region Start attached property
public static DependencyProperty ExactProperty = DependencyProperty.RegisterAttached("Exact", typeof(int), typeof(ShelfPanel),
new FrameworkPropertyMetadata(0,
FrameworkPropertyMetadataOptions.AffectsArrange | // Does this options have auto action?
FrameworkPropertyMetadataOptions.AffectsRender)); // Does this options have auto action?
public static void SetExact(UIElement element, int value)
{
element.SetValue(ExactProperty, value);
}
public static int GetExact(UIElement element)
{
return (int)element.GetValue(ExactProperty);
}
#endregion
protected override Size MeasureOverride(Size availableSize)
{
Size final = new Size();
foreach (UIElement child in InternalChildren)
{
child.Measure(availableSize);
final.Height += child.DesiredSize.Height;
}
return final;
}
protected override Size ArrangeOverride(Size finalSize)
{
foreach (UIElement child in InternalChildren)
{
Point position = new Point();
int exact = ShelfPanel.GetExact(child);
// Calculate position based on attached Exact
position.X = exact * 100;
position.Y = exact * 100;
child.Arrange(new Rect(position, child.DesiredSize));
}
return finalSize;
}
}
<local:ShelfPanel>
<local:Box local:ShelfPanel.Exact="0" MouseDown="Box_MouseDown"/>
<local:Box local:ShelfPanel.Exact="1" />
<local:Box local:ShelfPanel.Exact="2" />
</local:ShelfPanel>
public partial class MainWindow : Window // Codebehind for previous xaml
{
public MainWindow()
{
InitializeComponent();
}
private void Box_MouseDown(object sender, MouseButtonEventArgs e)
{
// I certainly sure this code get triggered after click.
ShelfPanel.SetExact(sender as UIElement, 3);
}
}
This works perfect <local:Box> are arranged as planned.
As you can deduce from code, after click on first <local:Box> it should change it position to 3, just after others 2. But surprisingly nothing happen.
Doesn't FrameworkPropertyMetadataOptions.Affects Arrange or FrameworkPropertyMetadataOptions.AffectsRender automatically repaint panel?
To make this works I need to add PropertyChangedCallbackand call there InvalidateVisual()?
You are setting the attached property on a Box, but want the parent element of the Box, i.e. the ShelfPanel to be arranged.
You should therefore set FrameworkPropertyMetadataOptions.AffectsParentArrange:
public static readonly DependencyProperty ExactProperty =
DependencyProperty.RegisterAttached("Exact", typeof(int), typeof(ShelfPanel),
new FrameworkPropertyMetadata(0,
FrameworkPropertyMetadataOptions.AffectsParentArrange));

Why does the custom panel not refreshing automatically

I have written a custom panel. Here is the code:
public class GameBoardPanel:Panel
{
public GameBoardPanel() { }
public static readonly DependencyProperty SquareSideLengthProperty =
DependencyProperty.Register("SquareSideLength", typeof(int), typeof(GameBoardPanel), new PropertyMetadata(0));
public int SquareSideLength
{
get { return (int)GetValue(SquareSideLengthProperty); }
private set { SetValue(SquareSideLengthProperty, value); }
}
public static readonly DependencyProperty RowsProperty =
DependencyProperty.Register("Rows", typeof(int), typeof(GameBoardPanel), new PropertyMetadata(0));
public int Rows
{
get { return (int)GetValue(RowsProperty); }
set { SetValue(RowsProperty, value); }
}
public int Columns
{
get { return (int)GetValue(ColumnsProperty); }
set { SetValue(ColumnsProperty, value); }
}
public static readonly DependencyProperty ColumnsProperty =
DependencyProperty.Register("Columns", typeof(int), typeof(GameBoardPanel), new PropertyMetadata(0));
public static readonly DependencyProperty RowProperty =
DependencyProperty.RegisterAttached("Row", typeof(int), typeof(GameBoardPanel));
public static readonly DependencyProperty ColumnProperty =
DependencyProperty.RegisterAttached("Column", typeof(int), typeof(GameBoardPanel));
public static void SetRow(DependencyObject control, int value)
{
control.SetValue(RowProperty, value);
}
public static int GetRow(DependencyObject control)
{
return (int)control.GetValue(RowProperty);
}
public static void SetColumn(DependencyObject control, int value)
{
control.SetValue(ColumnProperty, value);
}
public static int GetColumn(DependencyObject control)
{
return (int)control.GetValue(ColumnProperty);
}
protected override Size MeasureOverride(Size availableSize)
{
double min=Math.Min(availableSize.Width/Columns,availableSize.Height/Rows );
SquareSideLength=(int)min;
return new Size(SquareSideLength*Columns, SquareSideLength*Rows);
}
protected override Size ArrangeOverride(Size finalSize)
{
double min=Math.Min(finalSize.Width/Columns,finalSize.Height/Rows );
SquareSideLength=(int)min;
Size destinationSize = new Size(SquareSideLength * Columns, SquareSideLength * Rows);
foreach (UIElement element in base.InternalChildren)
{
int row = GameBoardPanel.GetRow(element);
int column = GameBoardPanel.GetColumn(element);
element.Arrange(new Rect(column * SquareSideLength, row * SquareSideLength,SquareSideLength, SquareSideLength));
}
return destinationSize;
}
}
It is very simple idea, similar to wpf Grid panel. I have a control which arrange its children on such a panel by setting children GameBoardPanel.Row and GameBoardPanel.Column attached properties. Let's assume that I have also a GameObject class which is a CustomControl and I added it to the panel. I want to move it for example to the left. So I do it in the following way:
GameObject movable=new GameObject();
//setting properties such as GameBoardPanel.Row and GameBoardPanel.Column
panel.Children.Add(movable);
GameBoardPanel.SetColumn(GameBoardPanel.GetColumn(movable)-1);
Let's skip the problem that the movable object can move outside the panel. It's not a big problem. However if I did the movement in that way I didn't see any effect. Only after adding an additional line:
panel.InvalidateArrange();
I observed that the object moved left. I'm quite sure, that if I would do the same with the wpf Grid, it's not necessary to call InvalidateArrange method. So, I am curious why does this happen? :D
You may set appropriate property metadata options to tell the framework that the Row and Column attached properties affect the layout of your custom panel:
public static readonly DependencyProperty RowProperty =
DependencyProperty.RegisterAttached("Row", typeof(int), typeof(GameBoardPanel),
new FrameworkPropertyMetadata(0,
FrameworkPropertyMetadataOptions.AffectsParentArrange));
public static readonly DependencyProperty ColumnProperty =
DependencyProperty.RegisterAttached("Column", typeof(int), typeof(GameBoardPanel),
new FrameworkPropertyMetadata(0,
FrameworkPropertyMetadataOptions.AffectsParentArrange));
That said, you should usually also measure the child elements in the MeasureOverride method:
protected override Size MeasureOverride(Size availableSize)
{
double min = Math.Min(availableSize.Width / Columns, availableSize.Height / Rows);
SquareSideLength = (int)min;
foreach (UIElement element in InternalChildren)
{
element.Measure(new Size(SquareSideLength, SquareSideLength));
}
return new Size(SquareSideLength * Columns, SquareSideLength * Rows);
}
Moreover it also doesn't seem to be necessary that SquareSideLength is a dependency property. It could as well be an ordinary CLR property (or probably just a private field). Its type may also better be double instead of int.
Finally, your MeasureOverride implementation should also be prepared for an infinite availableSize parameter value. From MSDN:
The available size that this
element can give to child elements. Infinity can be specified as a
value to indicate that the element will size to whatever content is
available.

Combining LineGeometry with EllipseGeometry (in code, not XAML)

I'm trying to create a custom shape with WPF. For starters I was just trying to create a simple line, that has a circle at each end (I know there are LineCaps, but that's not what I'm looking for).
I've looked into some tutorials and the easiest way to do that, seems to use a CombinedGeometry. However I can't get it to work properly. Here is my code that creates the geometry object:
protected override Geometry DefiningGeometry
{
get
{
Point ellipseCenter1 = new Point(X1 - this.CapDiameter / 2, Y1 - this.CapDiameter / 2);
Point ellipseCenter2 = new Point(X2 - this.CapDiameter / 2, Y2 - this.CapDiameter / 2);
var ellipse1 = new EllipseGeometry(ellipseCenter1, CapDiameter, CapDiameter);
var ellipse2 = new EllipseGeometry(ellipseCenter2, CapDiameter, CapDiameter);
var line = new LineGeometry(this.StartPoint, this.EndPoint);
var combined1 = new CombinedGeometry(GeometryCombineMode.Union, ellipse1, line);
var combined2 = new CombinedGeometry(GeometryCombineMode.Union, combined1, ellipse2);
// Freeze the geometry for performance benefits
combined2.Freeze();
return combined2;
}
}
However, for some reason, this doesn't draw the line. It draws both circles, but not the line. Obviously I'm missing something here, could someone point out what? :)
Just in case it matters, here is the rest of the class:
#region Dependency Properties
public static readonly DependencyProperty X1Property =
DependencyProperty.Register(
"X1",
typeof(double),
typeof(CappedLine),
new FrameworkPropertyMetadata(
0.0,
FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure
)
);
public static readonly DependencyProperty Y1Property =
DependencyProperty.Register(
"Y1",
typeof(double),
typeof(CappedLine),
new FrameworkPropertyMetadata(
0.0,
FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure
)
);
public static readonly DependencyProperty X2Property =
DependencyProperty.Register(
"X2",
typeof(double),
typeof(CappedLine),
new FrameworkPropertyMetadata(
0.0,
FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure
)
);
public static readonly DependencyProperty Y2Property =
DependencyProperty.Register(
"Y2",
typeof(double),
typeof(CappedLine),
new FrameworkPropertyMetadata(
0.0,
FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure
)
);
public static readonly DependencyProperty CapDiameterProperty =
DependencyProperty.Register(
"CapDiameter",
typeof(double),
typeof(CappedLine),
new FrameworkPropertyMetadata(
0.0,
FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure
)
);
#endregion
#region CLR Properties
public double X1
{
get { return (double)base.GetValue(X1Property); }
set { base.SetValue(X1Property, value); }
}
public double Y1
{
get { return (double)base.GetValue(Y1Property); }
set { base.SetValue(Y1Property, value); }
}
public double X2
{
get { return (double)base.GetValue(X2Property); }
set { base.SetValue(X2Property, value); }
}
public double Y2
{
get { return (double)base.GetValue(Y2Property); }
set { base.SetValue(Y2Property, value); }
}
public Point StartPoint
{
get { return (new Point(X1, Y1)); }
}
public Point EndPoint
{
get { return (new Point(X2, Y2)); }
}
public double CapDiameter
{
get { return (double)base.GetValue(CapDiameterProperty); }
set { base.SetValue(CapDiameterProperty, value); }
}
#endregion
And here is the XAML code I used to test it:
<Window x:Class="HG.WPF.Shapes.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:shapes="clr-namespace:Tomers.WPF.Shapes"
Title="WPF Custom Shapes" Height="300" Width="300" ResizeMode="NoResize">
<Canvas Background="Black">
<shapes:CappedLine X1="30" Y1="30" X2="200" Y2="200" CapDiameter="5" Fill="White" Stroke="White" StrokeThickness="2"></shapes:CappedLine>
</Canvas>
</Window>
Your LineGeometry objects will vanish if you try to Union them. From MSDN:
The GeometryCombineMode property specifies how the two geometries will
be combined. Note that CombinedGeometry combines the area specified by
two geometries, so geometries that do not have area (such as
LineGeometry) disappear when combined.
You can use GeometryGroup:
GeometryGroup combined = new GeometryGroup();
combined.Children.Add(ellipse1);
combined.Children.Add(ellipse2);
combined.Children.Add(line);
or you can use CombinedGeometry on the ellipse objects first, and then group that together with the line using GeometryGroup.

Categories