2017-06-19 96 views
0

我有一個Combobox定義在一個ItemsControl.的數據模板中。這個ComboBox有一個定義在其中的Button。在Button_Click事件中,應顯示Popup。這Popup包含一個自定義UserControl其中有一些控制內定義。如何防止Popup失去焦點?

以下是代碼之前,我解釋我的問題:

<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; 
} 

的問題是,當我點擊任何內部myCustomViewPopup定義的控件失去焦點並關閉。我如何強制它保持打開狀態?

編輯1:

由於myCustomView都有自己ViewModel我試圖通過這樣的視圖模型內的IsOpen屬性綁定到一個布爾值,以破解Popup保持開放:

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

+0

這個問題和你以前的問題有什麼區別? – mm8

+0

因爲現在我有一個關於失去焦點的具體問題。前面的問題是關於如何實際顯示Popup內部的視圖。在我看來,這個問題的目標被改變了。 –

+0

@ mm8它的工作。你可以在這裏發佈這個部分 –

回答

1

您可以在PlacementTarget設置爲父ItemsControl然後設置PopupVerticalOffsetHorizontalOffset屬性的屏幕,例如在指定其確切位置:

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

它的工作原理。爲了完整起見,將彈出按鈕放在按鈕上就足夠了: 'popup.VerticalOffset = p.Y - myCustomView.Height;'和 'popup.Horizo​​ntalOffset = p.X - myCustomView.Width;' –

0

您可以設置Popup.StaysOpen真這樣

<Popup StaysOpen="True"/> 
+0

除非它有不同的效果,我已經在'Button_Click'事件中做了這個:'popup.IsOpen = true;'。它的工作原理,因爲我可以點擊myCustomIView的背景,而沒有關閉Popup。問題是重點的改變 –

+0

不,我錯過了你的代碼示例。 – Gareth