Search code examples
c#wpfif-statementprismdelegatecommand

How to implement if, else statement in CanExecute command or Delegate command in wpf c#?


I'm new to WPF and Prism. How do I use an if else statement when using CommandCanExecute(), CommandExecute()/Delegate commands?

I have a code to load and get the instance of livechart. However, if the file for the chart does not exist in the users desktop, my application will crash. I want to implement a if else statement to say if you cannot find the graph, show up a message box notifying that there is an error, instead of crashing the program.

I tried searching up on RaiseCanExecuteChanged but unsure how to implement.

   private bool BEYieldCommandCanExecute()
    {
        return true;
    }

    private void BEYieldCommandExecute() 

    {
        if (true)
        {
            _eventAggregator.GetEvent<GraphPubSubEvent>().Publish(_viewName);

        }

        else
        {//Check
            MessageBox.Show("Error loading. Please ensure Excel file/Server file exist in Desktop/Server to generate Chart.", "Invalid Request", MessageBoxButton.OK, MessageBoxImage.Exclamation);
        }
    }

Thanks alot!!


Solution

  • In XAML: <Button Command="{Binding OpenDialogCommand }" />

    public class ViewModel
    {
        public DelegateCommand OpenDialogCommand { get; set; }
    
        public ViewModel()
        {
            OpenDialogCommand = new DelegateCommand(BrowseFile);
        }
    
        private void BrowseFile()
        {
            var openDialog = new OpenFileDialog()
            {
                Title = "Choose File",
                // TODO: etc v.v
            };
            openDialog.ShowDialog();
            if (File.Exists(openDialog.FileName))
            {
                // TODO: Code logic is here
    
    
            }
            else
            {
                // TODO: Code logic is here
            }
        }
    }
    

    `