首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WPF -如何激发MouseLeftButtonUp事件的ComboBox?

WPF -如何激发MouseLeftButtonUp事件的ComboBox?
EN

Stack Overflow用户
提问于 2019-02-12 19:45:35
回答 2查看 582关注 0票数 0

我有一个ComboBox,当用户选择一个项时,它必须调用一个需要ComboBox的selectedItem作为参数的函数。因为这个事件需要触发,即使项目没有改变,我也不能使用SelectionChanged事件。因此,为了解决这个问题,我想使用MouseLeftButtonUp,但是这个事件似乎不起作用。

我尝试使用触发的PreviewMouseLeftButtonUp事件,但是只有在事件发生后才修改ComboBox的selectedItem,这对我来说太晚了。

我也尝试过MouseLeftButtonDown事件,但它也不起作用。

WPF:

代码语言:javascript
复制
<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <ComboBox x:Name="cb" VerticalAlignment="Top" HorizontalAlignment="Left" IsHitTestVisible="True"
                  PreviewMouseLeftButtonUp="Cb_PreviewMouseLeftButtonUp"
                  MouseLeftButtonUp="Cb_MouseLeftButtonUp"
                  MouseLeftButtonDown="Cb_MouseLeftButtonDown"
                  SelectionChanged="Cb_SelectionChanged"/>
    </Grid>
</Window>

用于测试的C#:

代码语言:javascript
复制
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace WpfApp1 {
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();
            cb.Items.Add("a");
            cb.Items.Add("b");
        }
        private void Cb_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e) {
            Console.WriteLine("event : Preview mouse UP");
        }
        private void Cb_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) {
            Console.WriteLine("event : Mouse UP"); // Doesn't fire
        }
        private void Cb_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
            Console.WriteLine("event : Mouse DOWN"); // Doesn't fire either
        }
        private void Cb_SelectionChanged(object sender, SelectionChangedEventArgs e) {
            Console.WriteLine("event : selection changed"); // Only fire if the selected item change
        }
    }
}

基本上,我只想知道是否有可能触发MouseLeftButtonUp事件。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-02-13 21:32:45

多亏了mami,我找到了解决方案:

代码语言:javascript
复制
this.AddHandler(
    ComboBox.MouseLeftButtonUpEvent,
    new MouseButtonEventHandler(Cb_MouseLeftButtonUp),
    true
);

更多信息here

票数 0
EN

Stack Overflow用户

发布于 2019-02-12 20:00:45

即使您选择了已经选定的元素,DropDownClosed也会触发。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54657614

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档