Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RelayCommand and WeakReference

Tags:

mvvm-light

I have the following:

public MainViewModel(IDataService dataService)
{
    _dataService = dataService;

    NotWorkingCommand = new RelayCommand(() => 
    dataService.GetData((item, error) =>
    {
        if (error != null)
        {
            // Report error here
            return;
        }
        WelcomeTitle = item.Title;
    }));
}

Can someone please explain why my RelayCommand would stop firing after a while? I suspect it has to do with WeakReference used in the RelayCommand but I have no experience with WeakReference. If I used _dataService.GetData instead, it will work.

like image 404
wm_ Avatar asked Apr 23 '26 06:04

wm_


1 Answers

In your lambda expression, the dataService.GetData instruction won't work, because the scope of the variable dataService is only limited to the constructor.

Instead you should copy this reference to a backing field and call this instance instead. If think you were near the solution when you say it works by using _dataService.GetData.

private readonly IDataService _dataService;

public RelayCommand NotWorkingCommand { get; private set; }


public MainViewModel(IDataService dataService)
{
        _dataService = dataService;

        NotWorkingCommand = new RelayCommand(() =>
        _dataService.GetData((item, error) =>
        {
            if (error != null)
            {
                // Report error here
                return;
            }
            WelcomeTitle = item.Title;
        }));
    }

It seems that the delegate is correctly created because the reference exists when the relay command is created (in the scope of the ctor), but it can't be called at runtime because it cannot be evaluated correctly.

like image 53
marckm Avatar answered Apr 28 '26 05:04

marckm