2011-11-10 75 views
4

我使用this代碼來模擬我的Silverlight應用程序中的選項卡功能。作爲xaml中的事件處理函數的靜態函數

我真的很想避免寫這個函數很多次,因爲它必須在整個應用程序的很多文本框中使用。我創建了一個靜態類

public static class TabInsert 
{ 
    private const string Tab = " "; 
    public static void textBox_KeyDown(object sender, KeyEventArgs e) 
    { 
     TextBox textBox = sender as TextBox; 
     if (e.Key == Key.Tab) 
     { 
      int selectionStart = textBox.SelectionStart; 
      textBox.Text = String.Format("{0}{1}{2}", 
        textBox.Text.Substring(0, textBox.SelectionStart), 
        Tab, 
        textBox.Text.Substring(textBox.SelectionStart + textBox.SelectionLength, (textBox.Text.Length) - (textBox.SelectionStart + textBox.SelectionLength)) 
        ); 
      e.Handled = true; 
      textBox.SelectionStart = selectionStart + Tab.Length; 
     } 
    } 
} 

,這樣我可以從各個地方訪問它liek這個textBox.KeyDown += TabInsert.textBox_KeyDown;

有沒有一種方法可以讓我在XAML做到這一點?

回答

5

您可以創建一個Behavior(System.Windows.Interactivity命名空間),以輕鬆附加到OnAttached()覆蓋中訂閱該事件的文本框,並像在OnDetaching()中那樣執行處理並取消訂閱。

喜歡的東西:

public class TabInsertBehavior : Behavior<TextBox> 
{ 
    /// <summary> 
    /// Called after the behavior is attached to an AssociatedObject. 
    /// </summary> 
    /// <remarks> 
    /// Override this to hook up functionality to the AssociatedObject. 
    /// </remarks> 
    protected override void OnAttached() 
    { 
     base.OnAttached(); 
     this.AssociatedObject.KeyDown += textBox_KeyDown; 
    } 

    private const string Tab = " "; 
    public static void textBox_KeyDown(object sender, KeyEventArgs e) 
    { 
     TextBox textBox = sender as TextBox; 
     if (e.Key == Key.Tab) 
     { 
      int selectionStart = textBox.SelectionStart; 
      textBox.Text = String.Format("{0}{1}{2}", 
        textBox.Text.Substring(0, textBox.SelectionStart), 
        Tab, 
        textBox.Text.Substring(textBox.SelectionStart + textBox.SelectionLength, (textBox.Text.Length) - (textBox.SelectionStart + textBox.SelectionLength)) 
        ); 
      e.Handled = true; 
      textBox.SelectionStart = selectionStart + Tab.Length; 
     } 
    } 

    /// <summary> 
    /// Called when the behavior is being detached from its AssociatedObject, but before it has actually occurred. 
    /// </summary> 
    /// <remarks> 
    /// Override this to unhook functionality from the AssociatedObject. 
    /// </remarks> 
    protected override void OnDetaching() 
    { 
     base.OnDetaching(); 
     this.AssociatedObject.KeyDown -= textBox_KeyDown; 
    } 
} 
+2

在XAML中,你會做<我:Interaction.Behaviors><地方:TabInsertBehavior />

+0

我絕對贊同xyzzer - 附加的行爲是一個很好的解決方法。 (另見[如何在代碼中附加行爲](http://geekswithblogs.net/SilverBlog/archive/2009/09/22/behaviors-how-to-attach-behavior-in-code-behind-silverlight-3 .aspx)) – DmitryG

+0

我同意,但這隻會建立一個非常討厭的XAML,至少我想有,因爲有很多文本框需要此功能... –

4

不幸的是,there is no direct way to do this in XAML。您在後面的代碼中編寫的事件處理程序必須是實例方法,並且不能是靜態方法。這些方法必須由x:Class標識的CLR名稱空間中的部分類定義。您無法限定事件處理程序的名稱,以指示XAML處理器在不同的類範圍內尋找事件處理程序來處理事件連接。

+0

謝謝...然後後面的代碼它應該是... –