WPF弹出窗口在自定义上下文菜单打开时消失

时间:2016-05-17 11:34:38

标签: wpf xaml popup wpf-controls

我在PopUp中有一个TextBox。单击ToggleButton时,将打开PopUp窗口。

切换按钮代码

<ToggleButton Name="popupButton" Content="Click Me To Open Popup!" >
  <ToggleButton.Template>
    <ControlTemplate TargetType="ToggleButton">
      <Border Name="bg" RenderOptions.BitmapScalingMode="NearestNeighbor" RenderOptions.EdgeMode="Aliased"  Background="Transparent" Width="17" Height="15">
        <StackPanel HorizontalAlignment="Right" Width="17" >
          <Path RenderOptions.BitmapScalingMode="HighQuality" RenderOptions.EdgeMode="Aliased"  Data="M186,52 C208,52 230,52 252,52" Fill="Black" Margin="0,1.5" Stretch="Fill" Stroke="#457faa" StrokeThickness="2" />
          <Path RenderOptions.BitmapScalingMode="HighQuality" RenderOptions.EdgeMode="Aliased"  Data="M186,52 C208,52 230,52 252,52" Fill="Black" Margin="0,1.5" Stretch="Fill" Stroke="#457faa" StrokeThickness="2" />
          <Path RenderOptions.BitmapScalingMode="HighQuality" RenderOptions.EdgeMode="Aliased"  Data="M186,52 C208,52 230,52 252,52" Fill="Black" Margin="0,1.5" Stretch="Fill" Stroke="#457faa" StrokeThickness="2" />
        </StackPanel>
      </Border>
    </ControlTemplate>
  </ToggleButton.Template>
</ToggleButton>

单击ToggleButton时,它将在包含TextBox的PopUp窗口之后打开。

弹出窗口代码

<Popup Name="testPopup" Placement="Bottom" PlacementTarget="{Binding ElementName=popupButton}" IsOpen="{Binding IsChecked, ElementName=popupButton}" StaysOpen="False">
  <StackPanel Orientation="Horizontal">
    <Label Content="Username: " Background="White"/>
    <TextBox Text="Please RightClick to copy the text." ContextMenuOpening="TextBox_ContextMenuOpening">
      <TextBox.ContextMenu>
        <ContextMenu>
          <MenuItem Command="ApplicationCommands.Copy"/>
        </ContextMenu>
      </TextBox.ContextMenu>
    </TextBox>    
  </StackPanel>
</Popup>

当用户点击PopUp中的TextBox时,我想调用ContextMenu开场事件,如下所示:

ContextMenuOpening事件的CodeBehind

private void OpenContextMenu(FrameworkElement e)
{
    if (e.ContextMenu != null) 
    {
        e.ContextMenu.IsOpen = true;
    }
}

private void TextBox_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
    e.Handled = true;
    this.OpenContextMenu(sender as FrameworkElement);
}

调用ContextMenuOpening的目的

我正在调用它的开幕活动,因为我想要停止父{1}}打开父上下文菜单。然后我想打开TextBox的ContextMenu(源元素)。这就是问题所在。

问题

一旦我从代码隐藏中打开ContextMenu,就会打开ContextMenu,但是当StayOpen属性设置为False时,PopUp会消失。我想将StayOpen用于False,因为它应该在焦点丢失后立即关闭。

0 个答案:

没有答案