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



我仍在学习如何使用事件处理程序
我想要的是:当我单击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)
    {
    }

这应该是您想要的。不过,我建议您对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();
}

相关内容

  • 没有找到相关文章

最新更新