在使用了WindowStyle="None"时,你可能想自定定义窗体的一些操作,拖动就是常用的。实现起来也很简单:
第一种:
Drag_MouseMove事件:
第一种:
<Window x:Class="TestWPFDrag.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
WindowStyle="None"
Title="MainWindow" Height="451" Width="775">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Height="40" MouseMove="Drag_MouseMove" Background="Transparent">
<Button Content="关 闭" Width="50" Name="btnClose" HorizontalAlignment="Right" Click="btnClose_Click" />
</Grid>
</Grid>
</Window>
第二种:
<!--<Window x:Class="TestWPFDrag.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
WindowStyle="None"
Title="MainWindow" Height="451" Width="775" MouseMove="Drag_MouseMove" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Height="40" >
<Button Content="关 闭" Width="50" Name="btnClose" HorizontalAlignment="Right" Click="btnClose_Click" />
</Grid>
</Grid>
</Window>-->
Drag_MouseMove事件:
private void Drag_MouseMove(object sender, MouseEventArgs e)
{
try
{
if (e.LeftButton == MouseButtonState.Pressed)
{
this.DragMove();
}
}
catch { }
}
就OK了。Drag_MouseMove如果放在了窗体上就意味着鼠标在整个窗体的任何部分都可拖动整个窗体;如果是在某个控件上,只有拖动这个控件才可以拖动窗体,当然如果再某个控件上拖动的话,最好设置该控件的Background="Transparent"。
代码下载: