-2

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

    }
4

1 回答 1

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();
}
于 2013-07-08T19:56:03.083 回答