2011-04-26 22 views
6

我在文本框上將IsTabStop設置爲false,我知道這使得控件無法獲得焦點,但根據Silverlight Forums,它仍應該能夠接收鼠標事件。在我的tbxTotal_MouseLeftButtonUp方法中,我有MouseLeftButtonUp事件連線和一個斷點,並且在調試過程中它永遠不會被擊中。 SL論壇中的線程現在已經很老了,所以也許這在某個地方的更新中發生了變化。我想要一個不能被選中的文本框,但仍然可以編輯。這真的很難嗎?IsTabStop = SL4文本框上的False

回答

3

我沒有意識到這一點,但似乎是這樣,此外,我似乎無法得到MouseLeftButtonUp觸發。 MouseLeftButtonDown確實會觸發,並使用它可以做到這一點。

<TextBox IsTabStop="False" MouseLeftButtonDown="TextBox_MouseLeftButtonDown" /> 

然後在代碼中,您可以像這樣處理事件。

private void TextBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) 
    { 
     var textBox = ((TextBox) sender); 
     textBox.IsTabStop = true; 
     textBox.Focus(); 
     textBox.IsTabStop = false; 
    } 

這可能是值得的包裝在一個CustomControl

public class FocusableTextBox : TextBox 
{ 
    protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) 
    { 
     if (!IsTabStop) 
     { 
      IsTabStop = true; 
      Focus(); 
      IsTabStop = false; 
     } 

     base.OnMouseLeftButtonDown(e); 
    } 
} 
+0

嘿,甚至沒有看到,如果MouseLeftButtonDown工作。只是表明假設是不好的。謝謝。 – seekerOfKnowledge 2011-04-26 14:14:42

+0

但令人討厭的是,只是調用.Focus on MouseLeftButtonDown不起作用,爲什麼你必須打開/關閉舞蹈:( – bendewey 2011-04-26 14:21:06

+2

另外,因爲我的文本框是在樹視圖中,一些奇怪的事情正在發生。文本框中,鼠標向下被觸發,我將IsTabStop設置爲true,將其設置爲焦點,在LostFocus中,我將IsTabStop設置爲false。但是,文本框所在的樹視圖項獲取焦點,因此取消了我剛纔執行的操作在樹狀視圖項目中IsTabStop設置爲false,所以我覺得奇怪的是它可以獲得焦點,但我也對它進行了攻擊。在我的文本框LostFocus事件中,我實際上把焦點重新放到了我的文本框中,然後直接在,將IsTabStop設置爲false。 – seekerOfKnowledge 2011-04-26 14:26:18

1

@seekerOfKnowledge:在LostFocus禁用IsTabStop是一個好方法,但你重新聚焦黑客是不必要的。由於IsTabStop的更改尚未生效,因此第一次沒有任何明顯效果。這種方法也可以與任何其他控制一起使用。

 var control = sender as Control; 
     if (control != null) 
     { 
      control.MouseLeftButtonDown += (sender, args) => 
       { //This event fires even if the control isn't allowed focus. 
        //As long as the control is visible, it's typically hit-testable. 
        if (!control.IsTabStop) 
        { 
         control.IsTabStop = true; 
         //threading required so IsTabStop change can take effect before assigning focus 
         control.Dispatcher.BeginInvoke(() => 
          { 
           control.Focus(); 
          }); 
        } 
       }; 

      control.LostFocus += (sender, args) => 
       { //Remove IsTabStop once the user exits the control 
        control.IsTabStop = false; 
       }; 
     }