Iva*_*čić 5 c# xaml event-handling silverlight-4.0
我正在使用此代码来模拟我的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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以我可以从各个地方访问它 textBox.KeyDown += TabInsert.textBox_KeyDown;
有没有办法在XAML中做到这一点?
不幸的是,在XAML中没有直接的方法.在后面的代码中编写的事件处理程序必须是实例方法,不能是静态方法.这些方法必须由x:Class标识的CLR命名空间中的partial类定义.您无法限定事件处理程序的名称,以指示XAML处理器在不同的类范围内查找事件连接的事件处理程序.
您可以创建一个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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3020 次 |
| 最近记录: |