2010-02-17 67 views
1

我在運行模式下切換ListViewItem的內容模板以啓用編輯項目。爲此,我使用Ok和Cancel選項顯示Panel,我需要用戶在移至其他項之前選擇其中的任何選項。我希望Panel的行爲類似於模式Dialog。 有什麼建議嗎?需要在wpf內容面板中保持焦點

高級謝謝, 達斯

回答

0

你可以試着聽聽PreviewLostKeyboardFocus事件並將其標記爲已處理的時候你不想讓焦點去。這是一個例子。我們有兩列,如果你把主要精力投入到第一列,你永遠不會從它,直到你單擊釋放對焦按鈕出門:

XAML

<Window x:Class="WpfApplication1.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Focus Sample" Height="300" Width="340"> 
    <Grid> 
    <Grid.ColumnDefinitions> 
     <ColumnDefinition Width="*"/> 
     <ColumnDefinition Width="*"/> 
    </Grid.ColumnDefinitions> 
    <GroupBox Header="Press Release Focus to leave"> 
     <StackPanel PreviewLostKeyboardFocus="StackPanel_PreviewLostKeyboardFocus"> 
     <TextBox/> 
     <Button Content="Release Focus" 
       Click="ReleaseFocusClicked"/> 
     </StackPanel> 
    </GroupBox> 
    <GroupBox Header="Try to switch focus here:" 
       Grid.Column="1"> 
     <TextBox/> 
    </GroupBox> 
    </Grid> 
</Window> 

C#

using System.Windows; 
using System.Windows.Input; 

namespace WpfApplication1 
{ 
    public partial class Window1 : Window 
    { 
    private bool _letGo; 

    public Window1() 
    { 
     InitializeComponent(); 
    } 

    private void StackPanel_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) 
    { 
     var uie = (UIElement) sender; 
     var newFocusDO = (DependencyObject)e.NewFocus; 
     if (!_letGo && !uie.IsAncestorOf(newFocusDO)) 
     { 
     e.Handled = true; 
     } 
    } 

    private void ReleaseFocusClicked(object sender, RoutedEventArgs e) 
    { 
     _letGo = true; 
    } 
    } 
} 

我正在做一次額外的檢查,以確保新的焦點目標是否屬於我們的面板。如果我們不這樣做,我們絕不會讓焦點離開目前關注的因素。值得一提的是,這種方法不會阻止用戶點擊UI中的其他按鈕。它只是關注焦點。

希望這會有所幫助。

乾杯,Anvaka。

+0

嗨Anvaka, 感謝您的答案,但正如您所說,它只會保持keyborad焦點,用戶可以點擊其他按鈕在用戶界面。我真的想限制用戶點擊UI中的其他按鈕。意味着要創建一個「Modal」控件。 謝謝, Das – Das 2010-02-21 05:23:18

+0

嗨Das,另一點...如果沒有其他任何幫助添加處理程序PreviewMouseDownEvent到Application.Current.MainWindow並標記它處理,只要你不想鼠標按鈕處理進一步... – Anvaka 2010-02-23 22:33:04