2011-11-10 46 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

谢谢...然后后面的代码它应该是... –