文本框事件处理程序的问题

时间:2013-07-08 19:20:09

标签: c# wpf event-handling

我还在学习如何处理事件处理程序。
我想要的是:当我点击txtMonday获得焦点时,我点击删除按钮以清除此选定的文本框。
问题是:当我单击所选文本框的删除按钮时,所有未选中的文本框都是清除的。我只想删除所选的文本框。如何解决这个问题呢?您的代码示例非常感谢。谢谢!我正在使用WPF和C#。

    private void btnRemoveClick(object sender, RoutedEventArgs e)
    {
        TextBox text = new TextBox();
        text.GotFocus += new RoutedEventHandler(txtMonday_GotFocus);
           txtMonday.Clear();


        text.GotFocus += new RoutedEventHandler(txtTuesday_GotFocus);
           txtTuesday.Clear();

    }

    private void txtMonday_GotFocus(object sender, RoutedEventArgs e)
    {

    }

    private void txtTuesday_GotFocus(object sender, RoutedEventArgs e)
    {

    }

1 个答案:

答案 0 :(得分:3)

这应该做你想要的。我建议你做一些关于C#的研究,因为你的代码显示了一些基本的误解。

//you'll need a variable to store the last focused textbox.
TextBox txtLast;

public MainWindow()
{
    InitializeComponent();
    //add an event for all the textboxes so that you can track when one of them gets focus.
    txtSunday.GotFocus += txt_GotFocus;
    txtMonday.GotFocus += txt_GotFocus;
    txtTuesday.GotFocus += txt_GotFocus;
    txtWednesday.GotFocus += txt_GotFocus;
    txtThursday.GotFocus += txt_GotFocus;
    txtFriday.GotFocus += txt_GotFocus;
    txtSaturday.GotFocus += txt_GotFocus;

    //default to clearing sunday to avoid exception 
    //you could also let it clear a new TextBox(), but this is wasteful. Ideally, 
    //you would handle this case gracefully with an if statement, but I will leave that 
    //as an exercise to the reader. 
    txtLast = txtSunday;
}

private void txt_GotFocus(object sender, RoutedEventArgs e)
{
    //whenever you click a textbox, this event gets called. 
    //e.source is the textbox, but since it is is just an "Object" we need to cast it to a TextBox
    txtLast = e.Source as TextBox;
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    //this will clear the textbox which last had focus. If you click a button, the current textbox loses focus. 
    txtLast.Clear();
}
相关问题