【问题标题】:Button hold down to repeat commands按住按钮重复命令
【发布时间】:2023-03-13 18:41:01
【问题描述】:

我的 WPF 项目中有一个按钮,当我按住该按钮时,我希望它一遍又一遍地执行相同的命令。我可以使用RepeatButton,但我的偏好是命令一旦完成运行(在它自己的任务中)就再次执行,而不是依赖RepeatButton控件的延迟和间隔属性。

我不介意创建一个按钮单击方法,但是命令操作运行时间很长,执行时间将取决于 ExecuteParameter 的值(在这种情况下,代表机器物理位置的双精度元组)。

XAML:

<Button FontFamily="Marlett" FontSize="40" Content="5" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="100" Width="100" Height="50"                            
        Command="{Binding IncrBAnglePos}" 
        CommandParameter="{Binding ElementName=slider, Path=Value}">
</Button>

C#:

SystemCommands.AddSubSystemCommand(SystemRef, CommandNames.IncrAngle, new RelayCommand(             
        o => 
        {
            double AngleIncr = (double)o > 5 ? 5 : (double)o;
            double nextX = MotionControl.LiveX;
            double nextB = MotionControl.LiveB + AngleIncr;
            nextB = nextB >= 45 ? 45 : nextB;       
                Task.Run(() =>  
                {
                    SystemCommands.ExecuteCommand(CommandNames.GotoPosition, new Tuple<double,double>(nextX, nextB));
                });
        },       
        _ => 
        {
            if (MotionControl == null)
                return false;
            return !MotionControl.InMotionCheckStatus;
        }));
if (MotionControl != null)
{
    MotionControl.MotionChanged += SystemCommands.GetRelayCommand(CommandNames.IncrAngle).CanExecutePropertyChangedNotification;
}

更新:我可以看到一些人已经探出了头。如果有人对我如何改进问题本身有任何建议,我会欢迎反馈。从我缺乏声誉的角度来看,您可能会推测我在这方面是新手。

【问题讨论】:

  • btw 第二个 lambda 可以简化:_ =&gt; MotionControl != null &amp;&amp; !MotionControl.InMotionCheckStatus
  • 很好的建议。谢谢阿巴蒂舍夫。当我尝试让所有组件正常工作时,它现在既冗长又奇怪。我会在发布之前进行重构。

标签: c# wpf relaycommand


【解决方案1】:

Repeat Button 应该可以满足您的需求

Interval -> 重复开始后重复之间的时间量,以毫秒为单位。该值必须为非负数。

Delay -> 在开始重复之前,RepeatButton 在按下时等待的时间量(以毫秒为单位)。

<RepeatButton  FontFamily="Marlett" 
        Delay="500" 
        Interval="100" 
        FontSize="40" 
        Content="5" 
        HorizontalAlignment="Center" 
        VerticalAlignment="Top" 
        Margin="100" 
        Width="100" 
        Height="50"        
        Command="{Binding IncrBAnglePos}" 
        CommandParameter="{Binding ElementName=slider, Path=Value}">
</RepeatButton>

【讨论】:

  • Terrance,我很高兴自己犯了错误,并了解到 RepeatButton 控件在命令绑定上的效果与在按钮单击方法上的效果一样好。感谢所有为我看这个的人。
猜你喜欢
  • 2016-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-23
  • 2013-08-11
  • 2018-12-19
  • 1970-01-01
相关资源
最近更新 更多