如果我只有一些有限的事件可用,我该如何实现Changed事件

本文关键字:事件 何实现 实现 Changed 如果 | 更新日期: 2023-09-27 18:20:16

我知道下面的代码设计得太糟糕了,但我必须在一些供应商发明的有限框架上实现该事件。

我正在处理控件例如UserControl,它有许多TextBox控件。

UserControl类似于供应商提供的Excel。

此控件具有以下事件

"CellBeginEdit" 。。。当你集中注意力控制时,它就会开火。

"CellEditEnded" 。。。当你把注意力集中在其他控件上时,它就会启动。

"CellEditEnding" 。。。当你聚焦其他控件时,它就会启动。

"CellEnter" 。。。当您聚焦控件中的单元格时,它会激发。

"CellLeave" 。。。当您聚焦控件中的其他单元格时,它会激发。

这是在单元格中编辑文本的所有事件。

但是,我需要在所有单元格中实现TextChanged事件。

这是我的密码。

    private void CellBeginEdit(object sender, CellBeginEditEventArgs e)
    {
        //Get the element before Editing 
        Cell cell = currentCell;        
    
        //Not show. it requires to fire TextChanged event when textBox.Text = "something"; 
        TextBox textBox = new TextBox();
        textBox.Text = cell.Text;
        textBox.TextChanged += (s, ev) => MessageBox.Show("Done!");
        cell.Text = "Another Value";
        //I wish This code emerges "Done!" on Message Box.
    }

我试着做了,但效果不好。

我已经知道string的工作方式就好像Primitive Type在这种情况下一样,而C#、

因此,我将以上内容改写为以下内容。

    public TextBox textBox = new TextBox();
    private void changeData(ref string data)
    {
        textBox.Text = data;
    }
    private void CellBeginEdit(object sender, CellBeginEditEventArgs e)
    {
        Cell cell = currentCell;
        changeData(ref cell.Text);
        textBox.TextChanged += (s, ev) => MessageBox.Show("hoge");
        cell.Text = "Another Value";
    }

然而,这些代码会导致编译错误。

上面说我不能在Property中使用ref关键字。

为什么我不能在这里放置ref?我该如何实施活动?

编辑:

谢谢!我完全解决了。这就是代码。

        new Thread(
            delegate() {
                while (true)
                {
                    for (int i = 0; i < sheet.RowCount; i++)
                    {
                        if (sheet.Cells[i, 4].Text != "Before Value")
                        {
                            this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
                                new Action(
                                    () =>
                                      sheet.Cells[i, 5].Background = Brushes.Azure
                                )
                            );
                        }
                    }
                    Thread.Sleep(100);
                }
            }
        ).Start();

如果我只有一些有限的事件可用,我该如何实现Changed事件

这不起作用,因为字符串是不可变的。

你的问题不是你没有得到对字符串的引用,因为你已经得到了。问题是字符串永远不会改变。当单元格中的文本发生更改时,它不会更改包含文本的字符串,而是使用更改后的文本创建一个新字符串。

我认为为控件创建TextChanged事件的可能方法是使用反射侵入类的私有成员,或者使用计时器定期检查控件的Text属性以查看它是否已更改。