我正在嘗試制作一個容器 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(隱藏代碼):
public partial class DragWindowBorder : UserControl
{
#region Commands
public BaseCommand<Window> DragWindowCommand
{
get => new BaseCommand<Window>(/*async*/(window) => {
window.DragMove();
});
}
#endregion
public DragWindowBorder()
{
InitializeComponent();
}
}
基地命令.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 時,拖動作業正常
- 例如,當我呼叫包含 TextBox 或 Grid 的 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 在包含某些控制元件時似乎無法捕獲左鍵單擊。
你能幫我弄清楚如何解決這個問題嗎?
uj5u.com熱心網友回復:
我設法解決了我的問題。
1 - 對于 TextBox 示例,TextBox 位于我的 UserControl 上方,因此它捕獲左鍵單擊而不是我的 User 控制元件。
2 - 對于 Gid 示例,我需要在我的 UserControl 中設定背景,如下所示:
<UserControl x:Class="Default.Common.Controls.Views.DragWindowBorder"
...
Background="Transparent">
默認情況下,UserControls 沒有任何背景,因此如果它們填充有空組件(如我的示例中的空網格列),它們將無法捕獲滑鼠單擊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/313961.html
