簡體   English   中英

綁定RelayCommand不想執行

[英]Binding RelayCommand don't want to execute

我有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”時,什么都沒有發生。

我做錯了什么?

您正在使用默認構造函數在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;   
}

學分歸蘭德隨機公司所有。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM