是否可以使用参数重载事件处理程序?如果没有,通过另外3个参数的最佳方法是什么?
我不断收到错误消息:
以下是我想要实现的目标:
MainWindow.xaml.cs
public bool DotControl { get; set; }
public int Count { get; set; }
TextBox Tb = Keyboard.FocusedElement as TextBox;
private void RemoveLastButton_Click(object sender, RoutedEventArgs e, bool DotControl, int Count, TextBox tb)
{
if (Tb != null && Tb != DriverTextBox)
{
try
{
var keypadObject = new Keypad();
keypadObject.RemoveLast(Tb, DotControl, Count);
}
catch (Exception)
{
TotalTextBox.Focus();
}
}
else
{
TotalTextBox.Focus();
}
}
private void ResetButton_Click(object sender, RoutedEventArgs e, bool DotControl, int Count, TextBox tb)
{
if (Tb != null && Tb != DriverTextBox)
{
try
{
var keypadObject = new Keypad();
keypadObject.Reset(Tb, DotControl, Count);
}
catch (Exception)
{
TotalTextBox.Focus();
}
}
else
{
TotalTextBox.Focus();
}
}
Keypad.cs
// Backspace textbox
public void RemoveLast(TextBox tb, bool dotControl, int count)
{
if (tb.Text.Length > 0)
{
if (char.IsDigit(tb.Text[tb.Text.Length - 1])) count = 0;
else
{
dotControl = false;
count = 0;
}
tb.Text = tb.Text.Remove(tb.Text.Length - 1, 1);
}
}
// Clear textbox
public void Reset(TextBox tb, bool dotControl, int count)
{
dotControl = false;
count = 0;
tb.Text = "";
}
答案 0 :(得分:3)
事件处理程序具有特定签名,因此请从事件处理程序调用自定义方法。例如:
private void RemoveLastButton_Click(object sender, RoutedEventArgs e)
{
RemoveLastButton(DotControl, Count, tb)
}
private void RemoveLastButton(bool DotControl, int Count, TextBox tb)
{
if (Tb != null && Tb != DriverTextBox)
{
try
{
var keypadObject = new Keypad();
keypadObject.RemoveLast(Tb, DotControl, Count);
}
catch (Exception)
{
TotalTextBox.Focus();
}
}
else
{
TotalTextBox.Focus();
}
}
但是从您拥有的示例中,您甚至不需要将这些参数(DotControl, tb, Count
)传递给新的RemoveLastButton
方法,因为它们无论如何都是您的类的属性,因此可以访问。这意味着您甚至不需要突破这样的新方法,只需将代码放在事件处理程序中,但不必更改事件处理程序的签名。