0

During Executing my MainWindow program I am getting a null point reference in my predicate method.
The image link shows the error message I am having in MainViewModel class in which both MessageCanUse and ConsoleCanuse method throws null point reference: shotscreen

FYI- I know the method shown in the image is getting null in it, and the shown method should only run when I click the button of the show message. So why the method is running on building the solution.

My code flow - I have two buttons and one ComboBox in my XAML on selecting a message from the combo box and clicking the MessageBox button shows that message, but if the message selected is for Console then messageBox will automatically get disabled and vise versa for Console.WriteLine

MY MainViewModel Code-

      public class MainViewModel
    {
      public ObservableCollection<string> MyMessages { get; private set; }
      public RelayCommand MessageBoxCommand { get; private set; }
      public RelayCommand ConsoleLogCommand { get; private set; }
      public MainViewModel()
    {
        MyMessages = new ObservableCollection<string>()
        {
            "Kasim in Message Box",
            "Sakina",
            "Tim in Console Log",
            "Naama",
        };
        MessageBoxCommand = new RelayCommand(DisplayInMessageBox, MessageBoxCanUse);
        ConsoleLogCommand = new RelayCommand(DisplayInConsoleLog, ConsoleLogCanUse);
    }
    public void DisplayInMessageBox(object message)
    {
        MessageBox.Show(message.ToString());
    }
    public void DisplayInConsoleLog(object message)
    {
        Console.WriteLine(message.ToString());
    }

    public bool MessageBoxCanUse(object message)
    {
        if ((string)message == "Tim in Console Log")
        {
            return false;
        }

        return true;
    }
    public bool ConsoleLogCanUse(object message)
    {
        if (message.ToString().ToLower() == "Kasim in Message Box".ToLower())
        {
            return false;
        }

        return true;
    }

}

My RelayCommand Code-

    public class RelayCommand : ICommand
     {
   
       public Action<object> _execute;
       public Predicate<object> _canExecute;

    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
        {
            throw new NullReferenceException("execute");
        }

        _execute = execute;
        _canExecute = canExecute;
    }
    public RelayCommand(Action<object> execute) : this(execute, null)
    {
                                                        
    }
                                                             
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }
    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute(parameter);
    }

    public void Execute(object parameter)
    {
        _execute.Invoke(parameter);
    }
}

My xaml Code-

      <!--column 0-->
    <ComboBox x:Name ="ComboBoxMessages" MaxHeight="50" Grid.Column="0" ItemsSource="{Binding MyMessages}"></ComboBox>

    <!--Colmn 1-->
    <StackPanel Orientation="Vertical" Grid.Column="1">
        <Button Command="{Binding MessageBoxCommand}" CommandParameter="{Binding ElementName=ComboBoxMessages,Path=SelectedItem}">Message Box</Button>
        <Button Command="{Binding ConsoleLogCommand}" CommandParameter="{Binding ElementName=ComboBoxMessages,Path=SelectedItem}">Console Log</Button>
    </StackPanel>
EldHasp
  • 6,079
  • 2
  • 9
  • 24
kaszm
  • 51
  • 4
  • Sometimes this can be fixed by moving the CommandParameter attribute to before the Command attribute in your xaml. – ScottyD0nt Jul 30 '21 at 19:05
  • CanExecute is called initially to set the Button's IsEnabled state. You must implement it in a way that it can deal with a null parameter. – Clemens Jul 30 '21 at 19:06
  • Perhaps like `return !"Kasim in Message Box".Equals(message, StringComparison.OrdinalIgnoreCase);` – Clemens Jul 30 '21 at 19:13
  • Thanks, Clemens i would definitely try this – kaszm Jul 31 '21 at 02:53
  • In addition to @Clemens variant, you can add a null check to the "if" block: `if (message?.ToString().ToLower() ==...`. Or check the parameter for casting to the desired type (in this case, to string): `if (message is string str && str.ToLower() ==...`. – EldHasp Jul 31 '21 at 05:24
  • thankx a lot ELDHasp and Clemens for putting some time and giving me solution for my dumb error – kaszm Aug 09 '21 at 14:27

0 Answers0