这个问题是前一个问题的进一步发展。 我正在使用C#.NET framework 2.0,Visual Studios 10。 我有一个文本编辑器,我希望在表单标题中有一个脏标记,在这种情况下是一个简单的“”。如果文本框已更改,则“”应出现在标题中。保存文本框后,“*”应该消失。我尝试过以下的事情,但可能是错误的: 1表单,编辑器,具有保存按钮和文本框
---- Editor.cs
---- Functions.cs
一个不同的文件,而不是一个表单,Functions.cs,在执行保存时被调用 (为了保持整洁,只有表格代码上的按钮等,而不同的文件会造成污染)。
- 从第二个功能文件中更改Editor._isDirty值 - 从编辑器文件本身中更改_isDirty值 - 在编辑器中更改IsDirty(我无法弄清楚如何从功能文件中执行此操作)
以下是相关代码:
public static bool _isDirty = false;
public plainTextEditor()
{
InitializeComponent();
functionsProxy = new Functions();
IsDirty = false;
}
/* Property added to flag Changed _isDirty event */
public bool IsDirty
{
get { return _isDirty; }
set
{
if (_isDirty != value)
{
_isDirty = value;
OnIsDirtyChanged(IsDirty);
}
}
}
protected void OnIsDirtyChanged(bool _isDirty)
{
if (_isDirty == true)
{
//textBox1.BackColor = Color.LightCoral;
this.Text += "*";
}
else
{
this.Text = "Text Editor";
//textBox1.BackColor = SystemColors.Window;
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
string newtext = textBox1.Text;
if (currentText != newtext)
{
// This solves the problem of initial text being tagged as changed text
if (currentText == "")
{
//textBox1.BackColor = SystemColors.Window;
IsDirty = false;
}
else
{
IsDirty = true;
}
currentText = newtext;
}
}
private void btnSave_Click(object sender, EventArgs e)
{
functionsProxy.doSave(textBox1.Text);
//_isDirty = false;
IsDirty = false;
}
现在,根据我对事件和属性的理解..如果我甚至更改_isDirty的值,OnIsDirty应该调用并更改正确?无论我在哪里改变_isDirty的值,都说它来自不同的形式。这就是我想要的......根据_isDirty是否发生变化,*的事件会出现或消失!不知何故,它只是标记脏而不清除它。
如果可以,请提供帮助,或建议其他方法(示例代码为ace!);)
答案 0 :(得分:0)
您的代码中存在多个问题。其中之一是静态成员和方法中的参数的混淆。我试图纠正代码。以下是我的建议:
private bool _isDirty = false;
public plainTextEditor()
{
InitializeComponent();
functionsProxy = new Functions();
IsDirty = false;
}
/* Property added to flag Changed _isDirty event */
public bool IsDirty
{
get { return _isDirty; }
set
{
if (_isDirty != value)
{
_isDirty = value;
OnIsDirtyChanged();
}
}
}
private void OnIsDirtyChanged()
{
if (_isDirty == true)
{
//textBox1.BackColor = Color.LightCoral;
this.Text += "*";
}
else
{
this.Text = "Text Editor";
//textBox1.BackColor = SystemColors.Window;
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
string newtext = textBox1.Text;
if (currentText != newtext)
{
// This solves the problem of initial text being tagged as changed text
if (currentText == "")
{
//textBox1.BackColor = SystemColors.Window;
IsDirty = false;
}
else
{
IsDirty = true;
}
currentText = newtext;
}
}
private void btnSave_Click(object sender, EventArgs e)
{
functionsProxy.doSave(textBox1.Text);
IsDirty = false;
}
将“_isDirty”保密为您的表单。您已经使用属性IsDirty公开了Dirty状态。如果您不希望表单外部的任何代码更改IsDirty,则将setter(“set”)设为私有。 现在你的代码应该运行了。