【问题标题】:Binding RelayCommand don't want to execute绑定 RelayCommand 不想执行
【发布时间】:2019-03-13 12:58:54
【问题描述】:

我有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# wpf xaml command relaycommand


    【解决方案1】:

    您正在使用默认构造函数在 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。

    【讨论】:

    • 可能想在使用带参数的 ctor 时调用空 ctor。所以这条线public ExcelViewModel(IExcelService fileService) 可能应该是public ExcelViewModel(IExcelService fileService) : this() - 不会自动发生,如您在此处看到的:dotnetfiddle.net/XIKqdZ
    • @Rand - 我应该将“this”添加到我的第二个构造函数中吗?你能把它写成答案吗
    • @4est - 答案得到了正确更新,当您使用 constructor 的参数调用 constructor 时,您将面临同样的问题,因为现在您不会初始化 @ 987654330@ 在所述构造函数中,但仅在空的构造函数中 - 所以不是为两个构造函数修复它,你只是将问题从一个转移到另一个 - 通过调用 empty constructor 你初始化 CopyCommand 无论你使用什么 constructor
    • @Rand 我怎样才能正确地做到这一点?现在问题出在第一个或第二个 ctor
    • @4est - 正如我所说,答案得到了更新 - 它正确
    猜你喜欢
    • 2010-11-04
    • 1970-01-01
    • 2012-02-23
    • 2012-03-09
    • 1970-01-01
    • 2015-11-02
    • 2015-06-07
    • 2014-09-29
    • 2013-02-19
    相关资源
    最近更新 更多