如何从视图模型访问CommandParameter值

本文关键字:访问 CommandParameter 模型 视图 | 更新日期: 2023-09-27 18:01:04

我在视图中有一个按钮:

<Button Grid.Row="0" Grid.Column="1" Content="Export to CSV "  
        HorizontalAlignment="Right" VerticalAlignment="Center"
        Margin="2,2,20,2" Style="{StaticResource ExportButton}"
        Command="{Binding ExportToExcelCommand}"
        CommandParameter="{TelerikGrid}"
/>

现在我的ViewModel中的ExportCommand为:

private RelayCommand _exportToExcelCommand;
public ICommand ExportToExcelCommand
{
    get
    {
        if (_exportToExcelCommand == default(RelayCommand))
        {
            _exportToExcelCommand = new RelayCommand(ExportToExcel, CanExport);
        }
        return _exportToExcelCommand;
    }
}
private void ExportToExcel(Object param)
{
    try
    {
        //ToDo: Update With Command Parameters
        RadGridView gdv = new RadGridView();
        using (Stream stream = dialog.OpenFile())
        {
            gdv.Export(Columns);
        }
    }
    catch (FaultException ex)
    {
        var faultMessage = ex.Reason.GetMatchingTranslation().Text + "/n" + ex.StackTrace;
    }
}

现在我正在创建RadGridView:的一个新实例

RadGridView gdv = new RadGridView();

但是,我想从XAML 中作为CommandParameter传递的值中分配gdv

如何从视图模型访问CommandParameter值

RadGridView gdv = (RadGridView)param;

param是您发送的对象,所以只需将其投射到其原点即可。