我有画布。当我点击它时,我得到鼠标的坐标(向孩子添加)有一个custum控件(带有简单圆圈的拇指)。 在屏幕上,从逻辑上讲,左上角在添加时作为参考。我希望将拇指放在我点击的位置(见图片。红色星形=我点击的地方)。
要做什么,我需要获得拇指的实际宽度和高度,然后计算精确的坐标,将拇指的中心放在用户点击的位置。有没有更好的办法 ? 在WPF中,我使用了这段代码,但它在WinRT中不起作用。
//Circle in thumb
Ellipse Bdr = this.GetTemplateChild("Forme") as Ellipse;
DependencyObject dobj = VisualTreeHelper.GetParent(Bdr);
Vector ParentPosition = VisualTreeHelper.GetOffset((Visual)VisualTreeHelper.GetParent(dobj));
Vector BdrPosition = VisualTreeHelper.GetOffset((Visual)dobj);
return new Point((Position.X+BdrPosition.X) + Bdr.ActualWidth /2,(Position.Y+ ParentPosition.Y) + Bdr.ActualHeight / 2);
你能帮帮我吗?谢谢!
答案 0 :(得分:1)
ActualHeight
和ActualWidth
属性保持为0,直到FrameworkElement
未加载。另一方面,如果您在Ellipse
中调整了ControlTemplate
的大小,则可以在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));
}
}
希望它有所帮助。