You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin.Forms中点击DevExpress DataGridView表头触发空引用绑定异常

解决Xamarin.Forms中DevExpress DataGridView表头点击触发Tap事件的空引用错误

问题原因

点击表头时,Tap事件参数中没有绑定的数据对象(表头不属于数据行),如果事件处理程序里直接尝试访问或动态绑定这个不存在的对象,就会抛出Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Cannot perform runtime binding on a null reference'错误。

解决方案

有两种直接的解决方式:

方式一:在Tap事件处理程序中增加空值判断

修改dataTable_Tap方法,先检查目标数据是否为空,再执行后续逻辑:

private void dataTable_Tap(object sender, DataGridGestureEventArgs e)
{
    // 表头点击时e.Item为null,直接返回不执行后续逻辑
    if (e.Item == null)
        return;

    // 将e.Item转换为你的数据模型类型,再次判空
    var targetData = e.Item as YourDataModel;
    if (targetData == null)
        return;

    // 这里写你的业务逻辑
}

方式二:改用RowTap事件替代Tap事件

DevExpress DataGridView提供了专门的RowTap事件,该事件仅在点击数据行时触发,表头点击不会触发此事件,从根源避免空引用问题:

  1. 修改XAML代码:
<dxg:DataGridView Margin="0, 5, 0, 0" x:Name="dataTable" RowTap="dataTable_RowTap" >
</dxg:DataGridView>
  1. 编写对应的事件处理程序:
private void dataTable_RowTap(object sender, DataGridRowTapEventArgs e)
{
    var targetData = e.Item as YourDataModel;
    // 这里写你的业务逻辑
}

内容的提问来源于stack exchange,提问作者Mert Altiparmak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 16:34:50