Binding Button.Enabled to a property in C# dll
I'm currently writing a C# dll to be used as a back end Engine for GUI applications (windows forms) that wish to use it. The Engine can be in one of several pre-defined states, e.g. Loading, Idle, Working etc. which is controlled by a backgroundworker. I want the GUI applications which use this dll to be able to perform actions and bind control properties to properties within the engine, particularly the current state the engine is in. For example, I want applications which use the engine to disable actions and controls based on whether the Engine is running or not. To do this I've created a read only property within the engine as follows:
public Class Engine
{
// Make the class a singleton
private static Engine instance;
public static Engine Instance
{
get
{
if (instance == null)
instance = new Engine();
return instance;
}
}
// ... Class code altering the engines current state
public bool Property IsActive
{
get
{
return (EngineState != State.Idle);
}
}
}
Where State is an enumerator of all possible states and EngineState is the current state. To test this property out I've written a quick windows form application where I want a button to be Enabled if the engine is Active. To do this I've tried binding the Enabled property like so:
public Class TestApp
{
Engine MyEngine = Engine.Instance;
TestApp
{
Button_DoAction.DataBindings.Add("Enabled", MyEngine, "IsActive");
}
// ... Button handlers etc.
}
This binding seems to work when the application first loads but when the property IsActive changes within the dll, i.e. Engine goes from Active to Idle, the Enabled property 开发者_JAVA技巧of the button does not change.
So I'm just wondering whether what I'm trying to do is possible? Does the fact that Engine is a singleton and is written in an external dll mean make a difference? Any feedback would be a great help.
Thanks in advance.
your engine needs to implement System.ComponentModel.INotifyPropertyChanged
the interface has an event "ProperyChanged" which your engine must fire when something has changed (at least if you want something to react on that change)
see MSDN http://msdn.microsoft.com/en-gb/library/system.componentmodel.inotifypropertychanged%28v=vs.95%29.aspx
If you are using windows forms as the text suggests you'll need to raise an event or hand roll a delegate call back.
The form can then subscribe to the event/delegate and act accordingly.
If you aree using WPF as the code suggests then take the advice of DarkSquirrel42 and implement the INotifyPropertyChanged
interface.
精彩评论