[英]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.