静态函数作为xaml中的eventhandler

时间:2011-11-10 09:42:40

标签: c# xaml silverlight-4.0 event-handling

我正在使用this代码来模拟我的silverlight应用程序中的标签功能。

我真的很想避免多次编写函数,因为它必须在整个应用程序中的很多文本框中使用。我创建了一个静态类

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

这样我就可以从各个地方访问它了textBox.KeyDown += TabInsert.textBox_KeyDown;

我有办法在XAML中做到这一点吗?

2 个答案:

答案 0 :(得分:6)

不幸的是,there is no direct way to do this in XAML。您在后面的代码中编写的事件处理程序必须是实例方法,不能是静态方法。这些方法必须由x:Class标识的CLR命名空间中的partial类定义。您无法限定事件处理程序的名称来指示XAML处理器在不同的类范围内查找事件处理的事件处理程序。

答案 1 :(得分: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;
    }
}