I have created an ICommand that apart from executing some SQL procedures, it checks whether or not the MainWindow UI has been closed while the SQL procedures are executing. In case the MainWindow is closed by the user, the I want the application to simply stop by using the property return;
.
My problem is that the ICommand is inside an MVVM model. And this MVVM model is outside the MainWindow (Window class). So, when I try to call the base.OnClosed
I get an error that I cannot access it because of its protection level (Window methods are either protected or private).
How my code implementation looks like:
namespace Project
{
class ClosedClass //I turned it into a class because methods cannot be accessed outside the Window Class
{
public bool IsClosed {get; private set;}
protected override void OnClosed (EventArgs e)
{
base.OnClosed(e); //Error: object does not contain a definition for 'OnClosed'
//(Approach 2) MainWindow.OnClosed(e); //Error: is inaccessible due to its protection level
IsClosed=true;
}
}
public class MainWindowViewModel: INotifyPropertyChanged
{
public ICommand RunCommand
{
get {retun new DelegateCommand<object>(FuncRunCommand);)
}
public async void FuncRunCommand(object parameters)
{
await Task.Run(() => RunCustomMetod()); //inside this method lies the IsClosed statement
}
public void RunCustomMetod()
{
if(IsClosed) //Error: The name 'IsClosed' does not exist in the current context
{
return; //this stops the execution of the RunCustomMetod() if IsClose is true
}
}
}
public partial class MainWindow : Window
{
//...
}
}
Based on some research I did for similar questions I found out those two answers:
However, my inexperience with C# did not help me to understand how to solve my problem even though the answers were clear. Any suggestions? I appreciate your time and effort in advance.
[UPDATE -- based on the comments]
namespace Project
{
public class MainWindowViewModel: INotifyPropertyChanged
{
public bool IsClosed {get; private set;}
protected override void OnClosed(EventArgs e) //1.Error: MainWindowViewModel.OnClosed(EventArgs)': no suitable method found to override
{
MainWindow.OnClosed(e) //2.Error: Inaccessible due to its protection level
((MainWindowViewModel)DataContext).IsClosed = true; //3.Error: 'DataContext' does not exist in the current context.
}
public ICommand RunCommand
{
get {retun new DelegateCommand<object>(FuncRunCommand);)
}
public async void FuncRunCommand(object parameters)
{
await Task.Run(() => RunCustomMetod()); //inside this method lies the IsClosed statement
}
public void RunCustomMetod()
{
if(IsClosed) //Error: The name 'IsClosed' does not exist in the current context
{
return; //this stops the execution of the RunCustomMetod() if IsClose is true
}
}
}
public partial class MainWindow : Window
{
//...
}
}