动态弹出窗口在中心与关闭按钮

时间:2018-03-22 05:25:54

标签: wpf popup

我在窗口中有一个按钮。当我单击按钮时,它应该在按钮附近的弹出窗口中显示控件,当弹出窗口打开时,应该禁用父窗口。在我们创建自定义控件时,我必须在代码隐藏中实现它。

我尝试了以下代码。 pop正在打开但是在左上角没有关闭按钮。

 public MainWindow()
    {
        InitializeComponent();

        Button button = new Button();
        button.Width = 130;
        button.Content = "Table";
        button.Click += _buttonClicked;
        MyDock.Children.Add(button);
    }

    private void _buttonClicked(object sender, RoutedEventArgs e)
    {
        this.IsEnabled = false;
        DataGrid simpleTable = new DataGrid();
        simpleTable.ItemsSource = "ss,d,dd,ggg,rr,tt,yy".Split(',').Select(x => new Item() { Value = x }).ToList();
        DataGridTextColumn textColumn = new DataGridTextColumn();
        textColumn.Width = new DataGridLength(60, DataGridLengthUnitType.Pixel);
        simpleTable.Style = (Style)this.Resources["DataGridStyle"];
        textColumn.Binding = new Binding("Value");
        textColumn.ElementStyle = (Style)this.Resources["TextColumn"];
        simpleTable.Columns.Add(textColumn);
        Popup codePopup = new Popup();

        codePopup.Child = simpleTable;
        codePopup.VerticalAlignment = VerticalAlignment.Center;
        codePopup.HorizontalAlignment = HorizontalAlignment.Center;
        codePopup.Placement = System.Windows.Controls.Primitives.PlacementMode.Center;
        codePopup.IsOpen = true;

        this.IsEnabled = true;
    }
}

public class Item
{
    public string Value { get; set; }
}

2 个答案:

答案 0 :(得分:0)

对于弹出窗口,您需要实现自己关闭的按钮。弹出窗口不包含内置关闭按钮。如果你不想自己实现它,也许你可以使用另一个控件,如消息框或其他任何东西。

对于定位,您应该添加如下的PlacementTarget:codePopup.PlacementTarget = MyDock;,以便弹出窗口知道相关的UIControl。

答案 1 :(得分:0)

听起来你想要一个模态对话窗口。试试这个:

private void _buttonClicked(object sender, RoutedEventArgs e)
{
    DataGrid simpleTable = new DataGrid();
    simpleTable.ItemsSource = "ss,d,dd,ggg,rr,tt,yy".Split(',').Select(x => new Item() { Value = x }).ToList();
    DataGridTextColumn textColumn = new DataGridTextColumn();
    textColumn.Width = new DataGridLength(60, DataGridLengthUnitType.Pixel);
    simpleTable.Style = (Style)this.Resources["DataGridStyle"];
    textColumn.Binding = new Binding("Value");
    textColumn.ElementStyle = (Style)this.Resources["TextColumn"];
    simpleTable.Columns.Add(textColumn);

    Window codePopup = new Window();
    codePopup.SizeToContent = SizeToContent.WidthAndHeight;
    codePopup.WindowStyle = WindowStyle.ToolWindow;
    codePopup.Owner = this;
    codePopup.Content = simpleTable;
    codePopup.VerticalAlignment = VerticalAlignment.Center;
    codePopup.HorizontalAlignment = HorizontalAlignment.Center;
    codePopup.WindowStartupLocation = WindowStartupLocation.CenterOwner;
    codePopup.ShowDialog();
}

在弹出窗口关闭之前,ShowDialog()方法不会返回,这实际上意味着在此之前将禁用MainWindow