简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM