如何使用弹出控件来显示视图?

时间:2017-06-16 15:33:25

标签: c# wpf popup

我需要在点击按钮时显示视图。这是事件Click

的代码
private void Button_Click(object sender, RoutedEventArgs e)
{
    Button s = sender as Button;
    //some stuff needed to recognise which button was pressed
    myPopup.PlacementTarget = s;
    myPopup.Placement = System.Windows.Controls.Primitives.PlacementMode.Top;
    myPopup.IsOpen = true;
}

这是xaml

中定义的元素
<Popup IsOpen="False" StaysOpen="True" Name="myPopup">
       <view:myCustomView />
</Popup>

我有2个问题。

1-我的观点背景是黑色的,即使我没有设置它(我认为它应该是透明的?)

2-当我点击弹出窗口内的任何地方时,这只会消失

显示我的观点的正确方法是什么?我不想将拥有该按钮的ViewModel的任何内容绑定到这个具有自己的viewmodel的新视图

请注意,在事件Button_Click上,我会向ViewModel myCustomView发送一些参数,这些参数会改变其部分功能(这就是为什么我需要创建一个新的实例每次触发Button_Click事件时查看

编辑1:感谢EdPlunkett的回答,我能够用后台解决问题。我只需要设置AllowTransparency =“True”

EDIT2:

我按照建议通过Code Behind定义了我的Popup,所以我的代码现在是:

  private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button s = sender as Button;
            System.Windows.Controls.Primitives.Popup popup = new System.Windows.Controls.Primitives.Popup();
            popup.AllowsTransparency = true;
            popup.Child = new myCustomView();
            popup.PlacementTarget = s;
            popup.Placement = System.Windows.Controls.Primitives.PlacementMode.Top;
            popup.IsOpen = true;
            popup.StaysOpen = true;
        }

问题是,当我在myCustomView中定义的任何控件内部单击时,Popup会失去焦点并关闭。

1 个答案:

答案 0 :(得分:1)

我怀疑Popup是在另一个Popup中定义的,例如ComboBox的下拉列表,对吧?

您可以尝试在click事件处理程序中以编程方式创建Popup元素:

private void Button_Click(object sender, RoutedEventArgs e)
{
    Button s = sender as Button;
    System.Windows.Controls.Primitives.Popup popup = new System.Windows.Controls.Primitives.Popup();
    popup.AllowsTransparency = true;
    popup.Child = new myCustomView();
    //some stuff needed to recognise which button was pressed
    popup.PlacementTarget = s;
    popup.Placement = System.Windows.Controls.Primitives.PlacementMode.Top;
    popup.IsOpen = true;
    popup.StaysOpen = true;
}

这可以让您在弹出视图中单击而不关闭Popup。确保视图设置为Background

popup.Child = new myCustomView() { Background = Brushes.White };
  

我尝试了你的解决方案,虽然情况稍微好一点,但我仍然有结束问题。我可以在弹出窗口内单击而不关闭它,但是当我在我的视图中定义的任何文本框内单击时,弹出窗口关闭

因此,将PlacementTarget设置为父ItemsControl,然后设置VerticalOffset的{​​{1}}和HorizontalOffset属性,以在屏幕上指定其确切位置,例如:

Popup

您应该调整private void btn_Click(object sender, RoutedEventArgs e) { Button s = sender as Button; System.Windows.Controls.Primitives.Popup popup = new System.Windows.Controls.Primitives.Popup(); popup.AllowsTransparency = true; popup.Child = new myCustomView(); //some stuff needed to recognise which button was pressed popup.PlacementTarget = ic; //<-- "ic" is the name of the parent ItemsControl Point p = s.TranslatePoint(new Point(0, 0), ic); popup.VerticalOffset = p.Y; popup.HorizontalOffset = p.X; popup.IsOpen = true; popup.StaysOpen = true; } VerticalOffset的值以满足您的要求。