public abstract class Cell : INotifyPropertyChanged
{
protected string text;
protected string value;
readonly int rowIndex;
readonly int columnIndex;
public Cell()
{
}
public Cell(int ri, int ci)
{
rowIndex = ri;
columnIndex = ci;
}
public Cell CreateCell()
{
return this;
}
public string Value
{
get { return value; }
}
public int RowIndex
{
get { return rowIndex; }
}
public int ColumnIndex
{
get { return columnIndex; }
}
public string Text
{
get
{
return text;
}
set
{
text = value;
this.OnPropertyChanged("text");
}
}
public event PropertyChangedEventHandler PropertyChanged;
// Create the OnPropertyChanged method to raise the event
protected virtual void OnPropertyChanged(string propertyName = "")
{
var eventHandler = this.PropertyChanged;
if (eventHandler != null)
{
eventHandler.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public class SpreadSheet
{
private sCell[,] cellGrid;
private int rows, cols;
private int RowCount
{
get { return rows; }
}
private int ColumnCount
{
get { return cols; }
}
private class sCell : Cell
{
public sCell(int ri, int ci) : base(ri, ci)
{
}
public static sCell createCell(int ri, int ci)
{
return new sCell(ri, ci);
}
public void setValue(sCell[,] cellGrid)
{
string thisText = this.Text;
if (thisText[0] == '=')
{
byte[] asciiBytes = ASCIIEncoding.ASCII.GetBytes(thisText);
this.value = cellGrid[asciiBytes[1] - 65, asciiBytes[2]].Value;
}
else
{
this.value = thisText;
}
}
}
public event PropertyChangedEventHandler CellPropertyChanged;
public SpreadSheet(int numRows, int numColumns)
{
PropertyChangedEventHandler handler = CellPropertyChanged;
cellGrid = new sCell[numRows, numColumns];
rows = numRows;
cols = numColumns;
int i, j;
for (i = 0; i < rows; i++)
{
for(j = 0; j < cols; j++)
{
sCell newCell = sCell.createCell(i, j);
cellGrid[i, j] = newCell;
newCell.PropertyChanged += handler;
}
}
}
public Cell getCell(int ri, int ci)
{
if (cellGrid[ri, ci] != null)
{
return cellGrid[ri, ci];
}
else
{
return null;
}
}
protected void OnCellPropertyChanged(Cell c, string text)
{
PropertyChangedEventHandler handler = CellPropertyChanged;
if (handler != null)
{
handler(c, new PropertyChangedEventArgs(text));
}
}
private void handler(object sender, PropertyChangedEventArgs e)
{
sCell c = sender as sCell;
c.setValue(this.cellGrid);
OnCellPropertyChanged(sender as Cell, "CellValue");
}
}
为什么事件处理程序始终为null。我订阅从抽象Cell继承的Cell的每个实例到事件,它仍然保持为空。
答案 0 :(得分:0)
在SpreedSheet
构造函数中,删除以下行:
PropertyChangedEventHandler handler = CellPropertyChanged;
它看起来应该正确订阅 - 这会覆盖SpreadSheet.handler
方法。