wpf - 从 WPF 中的代码弹出窗口不起作用(在调整大小和切换窗口时)

标签 wpf button popup code-behind

我想在 WPF 中单击按钮时添加一个弹出窗口。我不想在我的 XAML 中添加弹出代码。它必须是背后的代码。

我的 XAML 如下::

<Window x:Class="Test.Window1"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      Title="Window1" Height="300" Width="300">
   <Grid>
     <Button x:Name="button1" Click="button1_Click">Button</Button>
   </Grid>
</Window>

我的 XAML 文件有一个简单的按钮。单击按钮时,我正在尝试执行以下代码。
  private void button1_Click(object sender, RoutedEventArgs e)
    {
        Button button = sender as Button;

        Popup codePopup = new Popup();
        TextBlock popupText = new TextBlock();
        popupText.Text = "Popup Text";
        popupText.Background = Brushes.LightBlue;
        popupText.Foreground = Brushes.Blue;
        codePopup.Child = popupText;

        codePopup.PlacementTarget = button;
        codePopup.IsOpen = true;

    }

但是为什么弹窗不是附着在 window 上 .我的意思是即使我切换窗口也会显示弹出窗口。还有当我调整窗口大小 , Popup 不再放置在按钮附近??

最佳答案

您也必须告诉弹出窗口显示自己。

codePopup.IsOpen = true;

this blog了解更多信息。

[编辑]
基本上,您的弹出窗口不是由任何父级“绑定(bind)”(或“拥有”),它独立于任何其他窗口和/或控件(等)。不幸的是,没有任何简单的方法可以解决这个问题。

您可能应该从 MSDN here 下载弹出位置示例.

代码示例使用带有 Rect 对象的 CustomPopupPlacement 类,并绑定(bind)到水平和垂直偏移量以移动 Popup。

关于wpf - 从 WPF 中的代码弹出窗口不起作用(在调整大小和切换窗口时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4212069/

相关文章:

c# - 在 WPF 的设计模式下获取源目录的路径

css - 触摸开始按钮

jquery - 将 Facebook 连接按钮更改为我自己的图像

javascript - 在同一个页面中打印,而不是在弹出的新单独页面中打印

c# - 使用 MVVM Light 解开两个控件上的 EventToCommand

wpf - 当文本框通过选项卡聚焦时光标不显示

javascript - 使用 AJAX 提交表单后重定向

.net - 错误: Cannot find the Style Property 'Template' on the type 'System.Windows.Controls.Primitives.Popup'

wpf - WPF中的分段文本框

Javascript 通过按钮关闭该功能