c# - 绑定 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”时,什么也没有发生。
我做错了什么?
解决方案
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。
推荐阅读
- c - 根据 fgetc(FILE*) 实现,我找不到 FILE 结构的 ungetcflag 成员
- git - 无法使用本地文件夹克隆 git repo
- azure - 使用 Azure AD 对本地(集成 Windows 身份验证)应用程序进行身份验证
- flutter - Flutter:ListView.builder 中的自动垂直高度
- hyperledger-fabric - 超级账本结构链代码:从链代码中调用另一个函数的函数?
- exception - Dart 异常处理无效
- outlook-web-addins - 使用 multipart/Form-data 进行休息 POST 查询
- android - 如何在android studio中使用相对布局时使(按钮)屏幕响应?
- node.js - 无法使用 Angular HttpClient 编辑设置 Post 请求正文我无法进行(放置、删除、发布任何请求,只有得到工作)
- android-studio - 更改后出现的 Gradle 和错误