該ActualHeight
和ActualWidth
屬性保持0,直到FrameworkElement
未加載。另一方面,如果您在ControlTemplate
中確定了尺寸Ellipse
,則可以在OnApplyTemplate()
上獲得尺寸。您可以使用代理將高度和寬度傳遞給容器Page
。即
ThumbControl
public class ThumbControl : Control
{
public IThumbSize thumbSize;
public ThumbControl()
{
this.DefaultStyleKey = typeof(ThumbControl);
}
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
Ellipse child = this.GetTemplateChild("circle") as Ellipse;
if (thumbSize != null)
thumbSize.SizeMeasured(child.Width, child.Height);
}
}
ThumbControl的伴奏
<Style TargetType="local:ThumbControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:ThumbControl">
<Ellipse x:Name="circle"
Fill="Blue"
Height="50"
Width="50"></Ellipse>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
IThumb接口
public interface IThumbSize
{
void SizeMeasured(double width, double height);
}
ContainerPage.xaml
<Grid Background="Black">
<Canvas x:Name="rootCanvas"
Background="Transparent"
PointerReleased="rootCanvas_PointerReleased"></Canvas>
</Grid>
ContainerPage.xaml.cs
public sealed partial class ContainerPage: Page, IThumbSize
{
ThumbControl thumbControl = new ThumbControl();
Point touchPoint = new Point();
public ContainerPage()
{
this.InitializeComponent();
thumbControl.thumbSize = this;
}
private void rootCanvas_PointerReleased(object sender, PointerRoutedEventArgs e)
{
PointerPoint pt = e.GetCurrentPoint(rootCanvas);
touchPoint.X = pt.Position.X;
touchPoint.Y = pt.Position.Y;
if (!rootCanvas.Children.Contains(thumbControl))
rootCanvas.Children.Add(thumbControl);
Canvas.SetLeft(thumbControl, touchPoint.X - (thumbControl.ActualWidth/2));
Canvas.SetTop(thumbControl, touchPoint.Y - (thumbControl.ActualHeight/2));
}
public void SizeMeasured(double width, double height)
{
Canvas.SetLeft(thumbControl, touchPoint.X - (width/2));
Canvas.SetTop(thumbControl, touchPoint.Y - (height/2));
}
}
希望它幫助。