how to move a button in WPF
XAML code is below
<Window x:Class="DenemeWpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DockPanel Width="Auto"
VerticalAlignment="Stretch"
Height="Auto"
HorizontalAlignment="Stretch"
Grid.ColumnSpan="1"
Grid.Column="0"
Grid.Row="0"
Margin="0,0,0,0"
Grid.RowSpan="1">
<StackPanel>
<StackPanel.Background>
<LinearGradientBrush>
<GradientStop Color="White" Offset="0" />
<GradientStop Color="DarkKhaki" Offset=".3" />
<GradientStop Color="DarkKhaki" Offset=".7" />
<GradientStop Color="White" Offset="1" />
</LinearGradientBrush>
</StackPanel.Background>
<StackPanel Margin="10">
<Button Name="simpleButton"
Click="simpleButtonClick"
KeyDown="simpleButton_KeyDown">Simple</Button>
<Button Name="cubeButton"
Click="cubeButtonClick">Cube</Button>
</StackPanel>
</StackPanel>
<Viewport3D Name="mainViewport"
ClipToBounds="True">
<Viewport3D.Camera>
<PerspectiveCamera FarPlaneDistance="100"
LookDirection="-11,-10,-9"
UpDirection="0,1,0"
NearPlaneDistance="1"
Position="11,10,9"
FieldOfView="70" />
</Viewport3D.Camera>
<ModelVisual3D>
<ModelVisual3D.Content>
<DirectionalLight Color="White" Direction="-2,-3,-1" />
</ModelVisual3D.Content>
</ModelVisual3D>
</Viewport3D>
</DockPanel>
</Grid>
</Window>
this is inide XAML.cs
private void simpleButton_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.P) {
/开发者_开发百科/something to move the simpleButton
}
}
I want to move simpleButton
when P is pressed from keyboard, but I can't seem to find any method or way to do that.
if animation is not required just do
if (e.Key == Key.P)
{
cubeButton.Margin = new Thickness(60, 50, 50, 60);
}
left,top,right,bottom should be numbers
and you have added keydown
event
to button so button must be focused in order to receive the keydown
event
also look at TranslateTransform in WPF
to move the button within the grid you have to handle the keydown event of the MainWindow, see following example:
private void Grid_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.P)
{
button1.Margin = new Thickness(2, 2, 2, 2);
}
}
Also if you have not explained how the focus on the active form KeyDown event will not be recalled.
Bye
You can move it many ways. You could put it on a Canvas control and change its Canvas.Left or Canvas.Top. You could put it inside a Grid and change its Grid.Row or Grid.Column. Probably the most flexible way is to apply a TranslateTransform to it, which will also move it the amount you specify.
精彩评论