Reputation: 2201
I have a Grid in my application and I want to move it around using four buttons (up, down, left, right). I have the grid's position (X and Y), but I don't know how to set a new position.
Upvotes: 2
Views: 875
Reputation: 35126
The way to move the grid depends on the container that it is contained in. If it is placed inside a Canvas then you can just bind the Canvas.Left and Canvas.Top properties of the grid to some properties in your viewmodel and you can then change those numbers on up and down buttons like so:
<Canvas Width="400" Height="400">
<Grid Height="20" Width="20" Canvas.Left="{Binding GridLeft}" Canvas.Top="{Binding GridTop}" Background="Red" />
</Canvas>
And ViewModel will be like this
class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
int gridLeft;
public int GridLeft
{
get { return gridLeft; }
set
{
gridLeft = value;
PropertyChanged(this, new PropertyChangedEventArgs("GridLeft"));
}
}
int gridTop;
public int GridTop
{
get { return gridTop; }
set
{
gridTop = value;
PropertyChanged(this, new PropertyChangedEventArgs("GridTop"));
}
}
}
Upvotes: 1
Reputation: 37174
On the keyboard down event, you can change the Margin property of the grid. This will work best if you have the grid nested within another Grid or Canvas. You have the keep the parent container in mind and how it will work with the layout.
Assuming it is nested in another Grid control, here is a sample of what the code might look like:
private void OnKeyDown( object sender, System.Windows.Input.KeyEventArgs e )
{
if( e.Key == System.Windows.Input.Key.Up )
{
Thickness orig = MyGrid.Margin;
MyGrid.Margin = new Thickness( margin.Left, margin.Up - 5, margin.Right, margin.Bottom );
}
else if( ... )
...
}
NOTE: You probably don't even need to allocate a new Thickness object. Just change the one that is there. This is purely for example's sake.
Upvotes: 1