在Mouse.AddPreviewMouseDownOutsideCapturedElementHandler注册的EventHandler永远不会命中

时间:2014-05-29 02:58:53

标签: c# wpf events

所以我正在尝试构建一个下拉颜色选择器自定义控件。我目前已将其设置为当我单击矩形部分弹出部分打开时。我想拥有它,当我点击控件外的任何地方时弹出窗口关闭。我写了MouseButtonEventHandler并在Mouse.AddPreviewMouseDownOutsideCapturedElementHandler注册了它。但是,无论我在窗口中单击的位置,处理程序都不会命中。我发现它很奇怪,因为WPF工具包中有两个使用此方法的控件。这两个是DropDownButton控件和CalculatorUpDown控件。我错过了任何会阻止处理程序解雇的内容吗?

控制代码:

[TemplatePart(Name = DisplayColorPart, Type = typeof(Rectangle))]
[TemplatePart(Name = DropDownPart, Type = typeof(Popup))]
public class ColorPickerDropDown : Control
{
    private const string DisplayColorPart = "PART_DisplayColor";
    private const string DropDownPart = "PART_DropDown";


    private Rectangle _displayColorElement;
    private Popup _dropDownElement;


    public Rectangle DisplayColorElement
    {
        get { return _displayColorElement; }
        set
        {
            _displayColorElement = value;
            InitalizeDisplayColorElement();
        }
    }

    public Popup DropDownElement
    {
        get { return _dropDownElement; }
        set { _dropDownElement = value; }
    }



    public static readonly DependencyProperty CurrentColorProperty =
        DependencyProperty.Register("CurrentColor", typeof(Brush), typeof(ColorPickerDropDown),
        new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

    public Brush CurrentColor
    {
        get { return (Brush)GetValue(CurrentColorProperty); }
        set { SetValue(CurrentColorProperty, value); }
    }



    static ColorPickerDropDown()
    {
        DefaultStyleKeyProperty
            .OverrideMetadata(typeof (ColorPickerDropDown),
            new FrameworkPropertyMetadata(typeof (ColorPickerDropDown)));
    }

    public ColorPickerDropDown()
    {
        Mouse.AddPreviewMouseDownOutsideCapturedElementHandler(this, OutsideControlClick);
    }



    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();

        if (DisplayColorElement == null) DisplayColorElement = GetTemplateChild(DisplayColorPart) as Rectangle;
        if (DropDownElement == null) DropDownElement = GetTemplateChild(DropDownPart) as Popup;
    }


    private void InitalizeDisplayColorElement()
    {
        if (DisplayColorElement == null) return;

        DisplayColorElement.AddHandler(Rectangle.MouseLeftButtonDownEvent,
                                       new RoutedEventHandler(DisplayColorClick),
                                       handledEventsToo: true);
    }

    private void DisplayColorClick(object sender, RoutedEventArgs e)
    {
        DropDownElement.IsOpen = DropDownElement.IsOpen ? false : true;
    }

    public void OutsideControlClick(object sender, MouseButtonEventArgs e)
    {
        if (!DropDownElement.IsMouseOver && !DisplayColorElement.IsMouseOver)
        {
            DropDownElement.IsOpen = false;
        }
    }
}

控制风格:

<Style TargetType="{x:Type local:ColorPickerDropDown}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:ColorPickerDropDown}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">

                    <StackPanel Background="Transparent">
                        <Rectangle Name="PART_DisplayColor"
                                   Height="{TemplateBinding Height}"
                                   Width="{TemplateBinding Width}"
                                   Fill="{Binding CurrentColor, RelativeSource={RelativeSource TemplatedParent}}"/>
                        <Popup Name="PART_DropDown"
                               PlacementTarget="{Binding ElementName=PART_DisplayColor}"
                               Width="{Binding ElementName=PART_DisplayColor}"
                               StaysOpen="True"
                               AllowsTransparency="True">

                            <Border Background="DodgerBlue"
                                    BorderThickness="1"
                                    BorderBrush="AliceBlue"
                                    CornerRadius="0,0,0,15">
                                <StackPanel>
                                    <Rectangle Height="100"
                                               Width="98"/>
                                </StackPanel>
                            </Border>

                        </Popup>
                    </StackPanel>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

1 个答案:

答案 0 :(得分:0)

仅当您使用PreviewMouseDownOutsideCapturedElement方法启用鼠标捕获时,Mouse.Capture()附加事件才有效。因此,您需要在打开弹出窗口后立即开始捕获鼠标。当鼠标捕获处于活动状态时,遗憾的是IsMouseOver不能再使用了;您必须直接检查鼠标坐标(请参阅下面示例中的方法IsWithin)。

我修改了您的代码,如下所示(请参阅标有***的地方),这对我有用:

[TemplatePart(Name = DisplayColorPart, Type = typeof(Rectangle))]
[TemplatePart(Name = DropDownPart, Type = typeof(Popup))]
public class ColorPickerDropDown : Control
{
    private const string DisplayColorPart = "PART_DisplayColor";
    private const string DropDownPart = "PART_DropDown";

    private Rectangle _displayColorElement;
    private Popup _dropDownElement;

    public Rectangle DisplayColorElement
    {
        get { return _displayColorElement; }
        set
        {
            _displayColorElement = value;
            InitalizeDisplayColorElement();
        }
    }

    public Popup DropDownElement
    {
        get { return _dropDownElement; }
        set { _dropDownElement = value; }
    }

    public static readonly DependencyProperty CurrentColorProperty =
        DependencyProperty.Register("CurrentColor", typeof(Brush), typeof(ColorPickerDropDown),
        new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

    public Brush CurrentColor
    {
        get { return (Brush)GetValue(CurrentColorProperty); }
        set { SetValue(CurrentColorProperty, value); }
    }

    static ColorPickerDropDown()
    {
        DefaultStyleKeyProperty
            .OverrideMetadata(typeof(ColorPickerDropDown),
            new FrameworkPropertyMetadata(typeof(ColorPickerDropDown)));

    }

    public ColorPickerDropDown()
    {
        Mouse.AddPreviewMouseDownOutsideCapturedElementHandler(this, OutsideControlClick);
    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();

        if (DisplayColorElement == null) DisplayColorElement = GetTemplateChild(DisplayColorPart) as Rectangle;
        if (DropDownElement == null) DropDownElement = GetTemplateChild(DropDownPart) as Popup;
    }

    private void InitalizeDisplayColorElement()
    {
        if (DisplayColorElement == null) return;

        DisplayColorElement.AddHandler(Rectangle.MouseLeftButtonDownEvent,
                                       new RoutedEventHandler(DisplayColorClick),
                                       handledEventsToo: true);
    }

    private void DisplayColorClick(object sender, RoutedEventArgs e)
    {
        DropDownElement.IsOpen = DropDownElement.IsOpen ? false : true;
        if (DropDownElement.IsOpen) // ***
        {                           // ***
            Mouse.Capture(this);    // ***
        }                           // ***
    }

    public void OutsideControlClick(object sender, MouseButtonEventArgs e)
    {
        if (!IsWithin(DropDownElement.Child, e) && !IsWithin(DisplayColorElement, e)) // ***
        {
            DropDownElement.IsOpen = false;
            Mouse.Capture(null); // ***
        }
    }

    // *** Is mouse within the bounds of the UI element?
    public static bool IsWithin(UIElement element, MouseButtonEventArgs e)
    {
        FrameworkElement elem = element as FrameworkElement;
        return (elem == null) ? false :
            new Rect(0, 0, elem.ActualWidth, elem.ActualHeight).Contains(e.GetPosition(element));
    }
}

请注意,您的XAML中存在一个小错字。这条线

Width="{Binding ElementName=PART_DisplayColor}"

应该是

Width="{Binding ElementName=PART_DisplayColor, Path=ActualWidth}"