简体   繁体   English

绑定RelayCommand不想执行

[英]Binding RelayCommand don't want to execute

I have got Page.xaml 我有Page.xaml

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

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

Here is my ExcelViewModel.cs 这是我的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. 但是,当我尝试运行“ CopyExcel”时,什么都没有发生。

What I'm doing wrong? 我做错了什么?

You are instantiating the ExcelViewModel class in the XAML using the default constructor. 您正在使用默认构造函数在XAML中实例化ExcelViewModel类。 Your CopyCommand is only initialized in the second constructor with parameter. 您的CopyCommand仅在带有参数的第二个构造函数中初始化。

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. 最好从Rand Random建议的任何特殊构造函数中调用默认构造函数。

This will not solve your problem (as your XAML view calls the default constructor)! 这不会解决您的问题(因为您的XAML视图调用了默认构造函数)! 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. 学分归兰德随机公司所有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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