绑定RelayCommand不想执行

问题描述 投票:0回答:1

我有Page.xaml

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

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

这是我的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);
}

但当我试图运行“复制Excel”时,没有发生任何事情。

我做错了什么?

c# wpf xaml command relaycommand
1个回答
2
投票

您正在使用默认构造函数在XAML中实例化ExcelViewModel类。您的CopyCommand仅在带参数的第二个构造函数中初始化。

将其更改为此应该可以正常工作:

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;   
}

更新:

从Rand Random建议的任何特殊构造函数中调用默认构造函数总是一个好主意。

这不会解决您的问题(因为您的XAML视图调用默认构造函数)!但作为参考,它将如下所示:

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;   
}

积分转到Rand Random。

© www.soinside.com 2019 - 2024. All rights reserved.