WPF Popup第一次没有打开

时间:2017-10-02 00:03:00

标签: c# wpf xaml

我试图创建一个用于选择颜色的弹出窗口。当我按下选择器按钮时弹出窗口打开,当选择颜色或用户在区域外单击时关闭弹出窗口。这是弹出窗口第一次打开时的工作原理。但在第一次打开弹出窗口后再也没有打开。

选择按钮类概述

public class RCTPaletteChooserButton : Button {

    public Popup popup { get { return GetTemplateChild("popup") as Popup; } }
    public RCTPaletteChooser chooser { get { return GetTemplateChild("chooser") as RCTPaletteChooser; } }

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

    }

    public override void OnApplyTemplate() {
        chooser.PaletteSelected += OnPaletteSelected;
        base.OnApplyTemplate();
    }

    private void OnPaletteSelected(object sender, PaletteEventArgs e) {
        popup.IsOpen = false;
        RemapColor = e.RemapColor;
        RaiseEvent(new PaletteEventArgs(PaletteSelectedEvent, e.RemapColor));
    }

    // None of these 3 overrides work
    protected override void OnMouseDown(MouseButtonEventArgs e) {
        RCTControls.PlayClick();
        popup.IsOpen = true;
        base.OnMouseDown(e);
    }
    protected override void OnMouseUp(MouseButtonEventArgs e) {
        popup.IsOpen = true;
        base.OnMouseUp(e);
    }
    protected override void OnLostMouseCapture(MouseEventArgs e) {
        popup.IsOpen = true;
        base.OnLostMouseCapture(e);
    }
}

选择按钮的内容模板。

<Style TargetType="{x:Type local:RCTPaletteChooserButton}">
    <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
    <Setter Property="Width" Value="12"/>
    <Setter Property="Height" Value="12"/>
    <Setter Property="IsTabStop" Value="False"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:RCTPaletteChooserButton}">
                <Grid>
                    <Image x:Name="image" Width="12" Height="12"/>
                    <Popup x:Name="popup" PlacementTarget="{Binding ElementName=image}"
                        Placement="Bottom" AllowsTransparency="True" StaysOpen="False">
                        <local:RCTPaletteChooser x:Name="chooser" Focusable="False"/>
                    </Popup>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

1 个答案:

答案 0 :(得分:0)

我通过修改选择器按钮类中的以下功能解决了这个问题。

protected override void OnMouseDown(MouseButtonEventArgs e) {
    popup.StaysOpen = true;
    popup.IsOpen = true;
    base.OnMouseDown(e);
}
protected override void OnMouseEnter(MouseEventArgs e) {
    popup.StaysOpen = false;
    base.OnMouseEnter(e);
}
protected override void OnMouseLeave(MouseEventArgs e) {
    popup.StaysOpen = false;
    base.OnMouseEnter(e);
}
protected override void OnLostMouseCapture(MouseEventArgs e) {
    // Function no longer needed
    base.OnLostMouseCapture(e);
}