单击左按钮时,WPF MouseDown冒泡事件不会冒泡

时间:2018-09-20 09:59:19

标签: c# wpf xaml

我有这样的XAML:

<Window x:Class="TreeViewTestingWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="500" Width="400">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <StackPanel Grid.Column="0" VerticalAlignment="Center" MouseDown="Control_MouseDown">
            <Button x:Name="button1" Width="80" Height="50" MouseDown="Control_MouseDown" Margin="10" >
                <Ellipse Width="30" Height="30" Fill="Red" MouseDown="Control_MouseDown" />
            </Button>
        </StackPanel>
        <TextBlock x:Name="textBlock1" Grid.Column="1" Padding="10" />
    </Grid>
</Window>

和方法“ Control_MouseDown()”:

private void Control_MouseDown(object sender, MouseButtonEventArgs e)
        {
            textBlock1.Text = textBlock1.Text + "sender: " + sender.ToString() + "\n";
            textBlock1.Text = textBlock1.Text + "source: " + e.Source.ToString() + "\n\n";
        }

当我使用右键或滚轮单击红色椭圆时,一切都很好,我得到了这样的预期结果:

pic 1

但是当我使用左键时事件不会冒泡,而我只会得到:

pic 2

为什么一切都会这样?

UPD Frenchy说,可能是Click事件“吃”了MouseDown,有可能避免这种行为吗?

1 个答案:

答案 0 :(得分:1)

当我使用PreviewMouseDown时一切正常

    <StackPanel Grid.Column="0" VerticalAlignment="Center" PreviewMouseDown="Control_MouseDown">
        <Button x:Name="button1" Width="80" Height="50" PreviewMouseDown="Control_MouseDown" Margin="10" >
            <Ellipse Width="30" Height="30" Fill="Red" PreviewMouseDown="Control_MouseDown" />
        </Button>
    </StackPanel>