鼠标按下事件未触发(冒泡事件)

时间:2010-12-21 07:32:50

标签: c# .net wpf .net-4.0

我是WPF的新手。我开始在WPF中学习RoutedEvents。我试了一个样本,我遇到了一个问题

    <Grid Margin="5" Name="Grid" MouseDown="Window_MouseUp">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"></RowDefinition>
        <RowDefinition Height="Auto"></RowDefinition>
        <RowDefinition Height="Auto"></RowDefinition>
    </Grid.RowDefinitions>
    <Label BorderBrush="Black" BorderThickness="1" Grid.Row="0" Margin="5"        Name="FancyLabel" MouseDown="Window_MouseUp" >
        <StackPanel Name="Stack" MouseDown="Window_MouseUp"> 
            <TextBlock Margin="3" Name="txtBlock1">
                Click Any Where
            </TextBlock>
            <TextBlock Margin="50" Name="txtBlock2" >
                Click me also
            </TextBlock>
        </StackPanel>
    </Label>
    <ListBox Grid.Row="1" Margin="5" Name="ListMessages"/>
    <Button Grid.Row="3" Margin="5" Name="cmd_Clear" MouseDown="Cmd_Clear_MouseDown"  >Clear</Button>
</Grid>

按钮的mouseDown事件的处理程序与树层次结构中的其他处理程序不同。事件没有解雇..

但是,如果我在.cs文件中添加以下代码

 Grid.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp),true);
 Stack.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp), true);
 FancyLabel.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp), true);
 txtBlock1.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp), true);
 txtBlock2.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp), true);
 Img1.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp), true);
 cmd_Clear.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Cmd_Clear_MouseDown), true);

触发Cmd_Clear_MouseDown事件,并将事件冒泡到网格,并且网格触发Window_MouseUp。

1 个答案:

答案 0 :(得分:1)

两点:

1)到处都有MouseDown="Window_MouseUp"吗?

2)为什么不使用Click而不是ClickMode="Press"注册MouseDown个活动。我不认为Button提供/提升MouseDown,除非可能使用自定义模板。

实施例

<Button Grid.Row="3"
        Margin="5"
        Name="cmd_Clear"
        ClickMode="Press"
        Click="Cmd_Clear_MouseDown">Clear</Button>