我在silverlight中创建了一个可拖动的用户控件,但在移动页面内的控件时遇到了问题。实际上问题是,拖动控件移动页面时拖动我不想要的。我希望控件只能在父控件中拖动。
任何帮助/建议都将不胜感激。
Below is the code used to perform operation:
XAML:
<Grid x:Name="LayoutRoot" >
<Grid.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform x:Name="LocalTranslateTransform"/>
</TransformGroup>
</Grid.RenderTransform>
C#:
private void OnToolbarClicked(object sender, MouseButtonEventArgs e)
{
mouseDownInToolbar = true;
DragOffset = e.GetPosition(LayoutRoot);
toolbarBorder.CaptureMouse();
}
private void OnToolbarMoving(object sender, MouseEventArgs e)
{
if (mouseDownInToolbar)
{
// we want to move it based on the position of the mouse
moveUserControl(e);
}
}
private void moveUserControl (MouseEventArgs e)
{
Point mousePos = e.GetPosition(LayoutRoot);
Double newX = LocalTranslateTransform.X + (mousePos.X - DragOffset.X);
Double newY = LocalTranslateTransform.Y + (mousePos.Y - DragOffset.Y);
LocalTranslateTransform.X = newX;
LocalTranslateTransform.Y = newY;
}
private void OnToolbarReleased(object sender, MouseButtonEventArgs e)
{
mouseDownInToolbar = false;
toolbarBorder.ReleaseMouseCapture();
}
答案 0 :(得分:4)
当您使用TranslateTransform
时,您将向合成器线程发送指令以在X / Y偏移处显示元素。它不遵守您的面板和任何可视树成员的规则。所以,你必须告诉合成器线程的边界。像这样使用Clip
:
<Grid Width="500" Height="500">
<Grid.Clip>
<RectangleGeometry Rect="0,0,500,500" />
</Grid.Clip>
<Grid x:Name="LayoutRoot">
<!-- This is the element being dragged by the mouse -->
</Grid>
</Grid>
RectangleGeometry
将创建允许子元素出现的边界。外面的任何东西都会被剪掉。
在完成所需的更改之后,这就是它的外观。
您需要创建约束。
计算您是否正在将实际控制转换为父级边界之外。
private void moveUserControl (MouseEventArgs e)
{
Point mousePos = e.GetPosition(LayoutRoot);
Double newX = LocalTranslateTransform.X + (mousePos.X - DragOffset.X);
Double newY = LocalTranslateTransform.Y + (mousePos.Y - DragOffset.Y);
var minX = 0;
var maxX = 500 - ActualWidth; // 500 is parent width
var minY = 0;
var maxY = 500 - ActualHeight; // 500 is parent height
if (newX < minX)
{
newX = minX;
}
else if (newX > maxX)
{
newX = maxX;
}
if (newY < minY)
{
newY = minY;
}
else if (newY > maxY)
{
newY = maxY;
}
LocalTranslateTransform.X = newX;
LocalTranslateTransform.Y = newY;
}