【问题标题】:programmatically bind button to double click command wpf以编程方式将按钮绑定到双击命令 wpf
【发布时间】:2016-08-01 14:21:54
【问题描述】:

我有以下ListBox

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

定义为ItemsSourceSequencesFilesObservableCollection&lt;Button&gt;

我正在使用以下函数手动将新的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);
}

是否可以在双击而不是单击时调用CommandPlaylistLoadCommand)?

【问题讨论】:

  • 我正在手动将新按钮添加到集合中... 好吧,这就是你的问题。您可能会以更简单的方式实现您的目标。您可能想回顾一下为什么您要这样做,并可能要求一种更好、更 mvvm/wpf-ish 的方式来实现您的目标。在另一个问题中。
  • 你能给我的答案投票吗(徽章和东西)?

标签: c# wpf mvvm command behavior


【解决方案1】:

您可以将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);

【讨论】:

    【解决方案2】:

    就像在这个问题中一样,我建议不要在您的 ViewModel 中创建用户控件:how to correctly bind a View control to a ViewModel List (WPF MVVM)

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

    【讨论】:

      猜你喜欢
      • 2013-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      • 1970-01-01
      • 2011-05-08
      • 2011-10-22
      • 2014-04-18
      相关资源
      最近更新 更多