I am working on a graphical application that relies heavily on delegates Action<>to customize the behavior of our user interface tools. I am wondering the way we do this is to have any potential problems, for example. Does the implementation implement references to captured variables, class instances, declaring delegates, etc.?
So, let's say we have this class MapControlthat wraps a stateful GUI control. The map has various types of tools (Drawing, Selection, etc.) represented by the interface ITool. You can install the tool with StartTool(), but you can only use one tool at a time, so when another tool is installed, the previous one stops with StopTool(). When the tool is stopped, a delegated call is made to the caller.
public class MapControl
{
ITool _currentTool;
Action<IResult> _onComplete;
public void StartTool(ToolEnum tool, Action<IResult> onComplete) {
if (_currentTool != null) StopTool();
_onComplete = onComplete;
_currentTool = CreateTool(tool) as ITool;
}
public void StopTool() {
IResult result = _currentTool.GetResult();
if (_onComplete != null)
_onComplete(result);
_onComplete = null;
_currentTool = null;
}
}
In the ViewModelapplication class , we install the following tool:
class ViewModel
{
private MapControl _mapControl = new MapControl();
public void SetSomeTool()
{
var someClassResource = this.SomeClassResource;
var someLocalResource = new object();
_mapControl.StartTool(ToolEnum.SelectTool, (IResult result) => {
someClassResource.DoSomething(result, someLocalResource);
});
}
}
ViewModel WPF, ViewModel. -, , , , ?
: callback? - , , ?
, ?