4est
4est

Reputation: 3168

Binding RelayCommand don't want to execute

I have got Page.xaml

<Page>
  <Page.DataContext>
        <vm:ExcelViewModel />
  </Page.DataContext>

  <Grid>
     <Button Command="{Binding Path=CopyCommand}" Margin="5"/>
  </Grid>
</Page>

Here is my ExcelViewModel.cs

public ExcelViewModel()
{
  SourcePath = @"\\test\\2019";
}

private readonly IExcelService fileService;
public ICommand CopyCommand{ get; private set; }

public ExcelViewModel(IExcelService fileService)
{
 this.fileService = fileService;   
 CopyCommand= new RelayCommand(CopyExcel);
}

But when I tried to run "CopyExcel" nothing is happend.

What I'm doing wrong?

Upvotes: 0

Views: 61

Answers (1)

Nicolas
Nicolas

Reputation: 828

You are instantiating the ExcelViewModel class in the XAML using the default constructor. Your CopyCommand is only initialized in the second constructor with parameter.

Change it to this and it should work:

public ExcelViewModel()
{
    SourcePath = @"\\test\\2019";
    CopyCommand= new RelayCommand(CopyExcel);
}

private readonly IExcelService fileService;
public ICommand CopyCommand{ get; private set; }

public ExcelViewModel(IExcelService fileService)
{
    this.fileService = fileService;   
}

Update:

It is always a good idea to call the default constructor from any special constructors as Rand Random suggested.

This will not solve your problem (as your XAML view calls the default constructor)! But for reference, it will look like this:

public ExcelViewModel()
{
    SourcePath = @"\\test\\2019";
    CopyCommand= new RelayCommand(CopyExcel);
}

private readonly IExcelService fileService;
public ICommand CopyCommand{ get; private set; }

public ExcelViewModel(IExcelService fileService) : this()
{
    this.fileService = fileService;   
}

Credits go to Rand Random.

Upvotes: 2

Related Questions