我试图使一个容器UserControl(像一个边界),它可以拖动当前窗口,当你按住左键点击UserControl内。
用户控件。XAML:
<UserControl.InputBindings>
<MouseBinding Gesture="LeftClick" Command="{Binding DragWindowCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}"/>
</UserControl.InputBindings>
UserControl.CS (Code Behind):
public partial class DragWindowBorder : UserControl
{
#region Commands
public BaseCommand<Window> DragWindowCommand
{
get => new BaseCommand<Window>(/*async*/(window) => {
window.DragMove();
});
}
#endregion
public DragWindowBorder()
{
InitializeComponent();
}
}
BaseCommand.CS:
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
}
我的问题如下:
- 当我调用包含TextBlock的UserControl时,拖动工作良好
- 当我调用包含文本框或网格的UserControl时,拖动不起作用
主窗口。XAML:
<!-- Working -->
<controls:DragWindowBorder>
<TextBlock Text="test"/>
</controls:DragWindowBorder>
<!-- Not Working -->
<controls:DragWindowBorder>
<TextBox Text="test"/>
</controls:DragWindowBorder>
<!-- Not Working -->
<controls:DragWindowBorder>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
</Grid>
</controls:DragWindowBorder>
由于某些原因,当包含某些控件时,我的UserControl似乎无法捕获左键。
你能帮我解决这个问题吗?
我终于解决了我的问题。
1 -对于TextBox的例子,TextBox在我的UserControl上,所以它捕获的是左键而不是我的User控件。
2 -对于Gid的例子,我需要在UserControl中设置一个背景,如下所示:
<UserControl x:Class="Default.Common.Controls.Views.DragWindowBorder"
...
Background="Transparent">
默认情况下,UserControls没有任何背景,所以如果它们被空组件填充(如我的示例中的空网格列),它们就不能捕获鼠标点击。