Designer auto-generating unwanted code I can't get rid of
I just created a control with the following code:
public partial class KindsEditor : NaviGroupList, INotifyPropertyChanged
{
private WebBrowser _Browser;
private BasicProject _Project;
public event PropertyChangedEventHandler PropertyChanged;
public bool RequiredDataLoaded { get { return (Project != null) && (Browser != null); } }
private bool _ButtonsEnabled = false;
public bool ButtonsEnabled { set { SetButtonsEnabled(value); } get { return _ButtonsEnabled; } }
public WebBrowser Browser
{
get { return _Browser; }
set
{
_Browser = value;
OnPropertyChanged(new PropertyChangedEventArgs("Browser"));
OnPropertyChanged(new PropertyChangedEventArgs("RequiredDataLoaded"));
}
}
public BasicProject Project
{
get { return null; }
set { LoadProject(value); }
}
public KindsEditor()
{
InitializeComponent();
DataBindings.Add("ButtonsEnabled", this, "RequiredDataLoaded");
}
private void SetButtonsEnabled(bool value)
{
newKindButton.Enabled = value;
_ButtonsEnabled = value;
OnPropertyChanged(new PropertyChangedEventArgs("ButtonsEnabled"));
}
protected void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != nul开发者_运维知识库l) PropertyChanged(this, e);
}
private void LoadProject(BasicProject value)
{
if (value != null) DataSource = value.Kinds;
_Project = value;
OnPropertyChanged(new PropertyChangedEventArgs("Project"));
OnPropertyChanged(new PropertyChangedEventArgs("RequiredDataLoaded"));
}
}
I removed some stuff that I think is irrelevant to my problem. I was trying to bind one button (newKindButton
) being enabled to two properties (Browser
and Project
) being not null. I know it's messy and no one would expect that I call OnPropertyChanged
while changing a different property and other stuff that might not be supposed to be done. I'll fix that later. But the weird thing is that the Form
that uses this control (I drag and dropped it from the toolbox) added this line to the InitializeComponent()
auto-generated code:
this.kindsEditor1.DataBindings.Add(new System.Windows.Forms.Binding("ButtonsEnabled", this.kindsEditor1, "RequiredDataLoaded", true));
So when I try to run the app I get an exception telling me that this line is trying to bind to the same property twice. I swear, I never added any binding from the properties panel. If I remove the line
DataBindings.Add("ButtonsEnabled", this, "RequiredDataLoaded");
from KindsEditor
's constructor, the auto-generated line disappears. Anyone knows what's going on?
Try adding DesignerProperties.GetIsInDesignMode
around the binding:
public KindsEditor()
{
InitializeComponent();
if (!DesignerProperties.GetIsInDesignMode(this))
DataBindings.Add("ButtonsEnabled", this, "RequiredDataLoaded");
}
I don't have a direct answer, but I suspect that Visual Studio thinks it needs to serialize something (the generated code) when it shouldn't. The above construct hides the binding from Visual Studio and only activates it during runtime.
精彩评论