如何防止Popup失去焦点?

时间:2017-06-19 08:45:30

标签: c# wpf popup lostfocus

我在Combobox的数据模板中定义了ItemsControl.ComboBox中定义了Button。在Button_Click事件中,应显示Popup。此Popup包含自定义UserControl,其中定义了一些控件。

在解释我的问题之前,这是代码:

<ComboBox x:Name="cb" HorizontalAlignment="Center" Grid.Column="2" Width="140" Visibility="{Binding HasCombobox, Converter={StaticResource BoolToVis}}">
    <ComboBox.ItemsSource>
       <CompositeCollection>
           <CollectionContainer Collection="{Binding Source={StaticResource cvs}}" />
           <ComboBoxItem>
              <Button Click="Button_Click" Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" Content="{x:Static prop:Resources.INSERT_BTN}"/>
           </ComboBoxItem>
       </CompositeCollection>
    </ComboBox.ItemsSource>
</ComboBox>

这是Button_Click事件:

private void Button_Click(object sender, RoutedEventArgs e)
{
    Button s = sender as Button;
    var 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:

由于myCustomView有自己的ViewModel,我试图通过将Popup属性绑定到视图模型中的布尔值来阻止IsOpen保持打开状态,如下所示:< / p>

popup.DataContext = myCustomViewModel;
Binding b = new Binding();
b.Source = myCustomViewModel;
b.Path = new PropertyPath("stayOpened");
b.Mode = BindingMode.TwoWay;
b.UpdateSourceTrigger = UpdateSourceTrigger.Default;
BindingOperations.SetBinding(popup, Popup.IsOpenProperty, b);
// BindingOperations.SetBinding(popup, Popup.StaysOpenProperty, b);  tried both IsOpened and StaysOpen

但焦点开关仍会杀死我的Popup

2 个答案:

答案 0 :(得分:1)

您可以将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; //adjust this value to fit your requirements
    popup.HorizontalOffset = p.X; //adjust this value to fit your requirements
    popup.IsOpen = true;
    popup.StaysOpen = true;
}

答案 1 :(得分:0)

您可以将Popup.StaysOpen设置为true,就像这样

<Popup StaysOpen="True"/>