tags:

views:

1190

answers:

2

HI,

How do I move (drag) a Grid Panel inside a WPF Window? The Grid Panel does not have a Position or Location or X and Y coordinate porperty. All I am looking at is to move the Grid Panel from its current location to a new location using Mouse so that the controls that are "burried" underneath it will show up.

Any pointers?

Many Thanks.

+1  A: 

Here's some code examples to get you started:

In XAML:

Create a grid and define a render transform on it:

<Grid x:Name="grid" Background="Blue" 
      Width="100" Height="100" 
      MouseDown="Grid_MouseDown" MouseMove="Grid_MouseMove" MouseUp="Grid_MouseUp">
    <Grid.RenderTransform>
        <TranslateTransform x:Name="tt"/>
    </Grid.RenderTransform>
</Grid>

Name the control that you want the grid to move within:

<Window x:Name="window" ...>
    <Grid x:Name="grid"...
</Window>

In code behind:

Point m_start;
Vector m_startOffset;

private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
{
    m_start = e.GetPosition(window);
    m_startOffset = new Vector(tt.X, tt.Y);
    grid.CaptureMouse();
}

private void Grid_MouseMove(object sender, MouseEventArgs e)
{
    if (grid.IsMouseCaptured)
    {
        Vector offset = Point.Subtract(e.GetPosition(window), m_start);

        tt.X = m_startOffset.X + offset.X;
        tt.Y = m_startOffset.Y + offset.Y;
    }
}

private void Grid_MouseUp(object sender, MouseButtonEventArgs e)
{
    grid.ReleaseMouseCapture();
}
Josh G
A: 

Just put the grid panel inside a canvas rather than directly into the window - this will then give it X/Y co-ordinates.

You can then implement the drag/drop behaviour using a custom attached property such as detailed here (http://www.deepcode.co.uk/archive/2008/11/16/using-attached-properties-to-compose-new-behaviour.aspx)

deepcode.co.uk