原文地址:用于拖动窗口的WPF UserControl容器 - 我爱学习网 (5axxw.com)
一.usercontrol去掉windos样式标题栏
<prism:Dialog.WindowStyle>
<Style TargetType="Window">
<Setter Property="prism:Dialog.WindowStartupLocation" Value="CenterScreen" />
<Setter Property="ShowInTaskbar" Value="False"/>
<Setter Property="SizeToContent" Value="WidthAndHeight"/>
<Setter Property="WindowStyle" Value="None"/>
<Setter Property="AllowsTransparency" Value="True"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
</prism:Dialog.WindowStyle>
二.增加左键事件
<UserControl.InputBindings>
<MouseBinding Gesture="LeftClick" Command="{Binding DragWindowCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}"/>
</UserControl.InputBindings>
三.创建类
public class BaseCommand<T> : ICommand
{
#region Variables
private readonly Action<T> _execute;
private readonly Func<T, bool> _canExecute;
public event EventHandler CanExecuteChanged;
#endregion
#region Methods
public BaseCommand(Action<T> execute) : this(execute, null) { }
public BaseCommand(Action<T> execute, Func<T, bool> canExecute)
{
if (execute == null)
{
throw new ArgumentNullException("execute");
}
_execute = execute;
_canExecute = canExecute;
}
public void OnCanExecuteChanged()
{
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
public bool CanExecute(object parameter)
{
return _canExecute == null || _canExecute((T)parameter);
}
public void Execute(object parameter)
{
if (CanExecute(parameter) && _execute != null)
{
T param = default(T);
try
{
param = (T)parameter;
}
catch { }
_execute(param);
}
}
#endregion
}
四. 实现事件代码
public BaseCommand<Window> DragWindowCommand
{
get => new BaseCommand<Window>(/*async*/(window) => {
window.DragMove();
});
}