首页 > 解决方案 > 绑定 RelayCommand 不想执行

问题描述

我有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);
}

但是当我尝试运行“CopyExcel”时,什么也没有发生。

我做错了什么?

标签: c#wpfxamlcommandrelaycommand

解决方案


ExcelViewModel您正在使用默认构造函数在 XAML中实例化该类。您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。


推荐阅读