以编程方式将按钮绑定到双击命令wpf

programmatically bind button to double click command wpf

我有以下 ListBox:

<ListBox x:Name="SequencesFilesListBox" ItemsSource="{Binding SequencesFiles, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Foreground="DarkBlue" BorderBrush="Transparent" />

定义为ItemsSourceSequencesFiles是一个ObservableCollection<Button>

我正在使用以下函数手动将新 Buttons 添加到集合中:

private void AddSequenceToPlaylist(string currentSequence)
{
    if (SequencesFiles.Any(currentFile => currentFile.ToolTip == currentSequence)) return; 

    var newSequence = new Button
    {
        ToolTip = currentSequence,
        Background = Brushes.Transparent,
        BorderThickness = new Thickness(0),
        HorizontalAlignment = HorizontalAlignment.Stretch,
        HorizontalContentAlignment = HorizontalAlignment.Stretch,
        Content = Path.GetFileName(currentSequence),
        Command = PlaylistLoadCommand,
        CommandParameter = currentSequence,
    };
    SequencesFiles.Add(newSequence);
}

是否可以在双击而不是单击时调用 Command (PlaylistLoadCommand)?

就像这个问题一样,我建议不要在您的 ViewModel 中创建用户控件:

对于双击绑定,不幸的是它在 WPF 工具包中仍然不受支持,请参阅这个问题:How to bind a command in WPF to a double click event handler of a control?

您可以将 InputBinding 设置为您的 Button 以在双击时触发您的命令

var newSequence = new Button
{
    ToolTip = currentSequence,
    Background = Brushes.Transparent,
    BorderThickness = new Thickness(0),
    HorizontalAlignment = HorizontalAlignment.Stretch,
    HorizontalContentAlignment = HorizontalAlignment.Stretch,
    Content = Path.GetFileName(currentSequence),
    CommandParameter = currentSequence,
};

var mouseBinding = new MouseBinding();
mouseBinding.Gesture = new MouseGesture(MouseAction.LeftDoubleClick);
mouseBinding.Command = PlaylistLoadCommand;
newSequence.InputBindings.Add(mouseBinding);