【问题标题】:Buttons are not working on single click Wpf按钮在单击 Wpf 时不起作用
【发布时间】:2013-08-22 11:21:12
【问题描述】:

在我的 wpf 应用程序中,我的按钮在单击时不起作用。我有用于更改 ListBox 项目的 dataTemplate 的编辑按钮。但是,我需要单击两次按钮才能进行编辑。同样对于右键单击事件,我需要单击两次。双击事件工作正常。为什么会发生这种情况?问题可能出在哪里?

右键事件和编辑按钮的C#代码:

private void listBox1_MouseRightClick(object sender, MouseButtonEventArgs e)
    {
        Harvest_TimeSheetEntry entryToDelete = (Harvest_TimeSheetEntry)listBox1.SelectedItem;

        if(entryToDelete!=null)
        {
            MessageBoxResult Result = System.Windows.MessageBox.Show("Are you sure?", "Delete Confirmation", System.Windows.MessageBoxButton.YesNo);

            if (Result == MessageBoxResult.Yes)
            {
                Globals._globalController.harvestManager.deleteHarvestEntry(entryToDelete);
                listBox1.Items.Remove(listBox1.SelectedItem);
            }
            else
            {
                System.Windows.MessageBox.Show("Delete operation Terminated");
            }
        }
    }

    private void EditButton_Click(object sender, RoutedEventArgs e)
    {
        if (listBox1.ItemTemplate == (DataTemplate)this.FindResource("DefaultDataTemplate"))
        {
            listBox1.ItemTemplate = (DataTemplate)this.FindResource("EditableDataTemplate");
            EditButton.Content = "Done Editing";
        }
        else
        {
            foreach (Harvest_TimeSheetEntry item in listBox1.Items)
            {
                if (!item.isSynced)
                {
                    ValidateEntry(item);
                    Globals._globalController.harvestManager.updateHarvestEntry(item);
                    System.Windows.MessageBox.Show("Entry Updated");
                }
                listBox1.ItemTemplate = (DataTemplate)this.FindResource("DefaultDataTemplate");
                EditButton.Content = "Edit";
            }
        }

    }

【问题讨论】:

  • 这可能与 ListBoxItem 模板有关,但如果没有更多细节,很难预测。每个列表框项都会对单击做出反应以更改选择状态,因此这可能是一个原因。尝试使用 Snoop 或 WPF Inspector 等工具查看控件的结构,以更好地了解正在发生的事情。您几乎可以编辑您的问题以删除代码,因为这与实际问题并没有真正的关系,只会增加噪音......
  • @MicrosoftDN 正如你所说,我已经添加了代码。但正如 Alex Paven 所说,我也认为代码与实际问题无关。
  • 可能是其他一些元素捕获并处理了事件,使用 snoop 来查看谁处理了这些事件...
  • 在 Wpf 应用程序中,如果我们单击一次它作为列表框事件,稍后如果我们再次单击它会触发子项事件。希望这可能是问题

标签: c# wpf button mouseclick-event


【解决方案1】:

尝试处理 PreviewMouseDown 或 PreviewMouseLeftButtonDown 事件。有时冒泡的Routed Events 会被控件内部使用。有关详细信息,请查看 MSDN 上的 UIElement.PreviewKeyDown Event 和 UIElement.PreviewMouseDown Event 页面。

【讨论】:

    猜你喜欢
    • 2014-09-26
    • 2014-03-24
    • 2017-03-09
    • 1970-01-01
    • 2015-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多