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

如何将TemplatedParent的Content属性正确赋值给变量?

错误原因

你的报错核心是两点:

  1. 没有对TemplatedParent做空校验和类型安全转换,直接强制转换会在类型不匹配/对象为空时抛出无效转换/空引用异常
  2. 如果点击事件的触发源是ItemTemplate内部的子元素,TemplatedParent指向的是该子元素的模板父级,未必直接是ListBoxItem实例

正确实现方案

方案1:从点击事件源向上遍历可视化树获取ListBoxItem(最稳妥)

private void OnListBoxItemClicked(object sender, RoutedEventArgs e)
{
    DependencyObject target = sender as DependencyObject;
    // 向上遍历可视化树找到父级ListBoxItem
    while (target != null && target is not ListBoxItem)
    {
        target = VisualTreeHelper.GetParent(target);
    }

    if (target is ListBoxItem item)
    {
        // 此处获取到的Content即为你需要的属性值,可按需转换为绑定的业务类型
        var itemContent = item.Content;
        // 后续校验逻辑可直接使用itemContent
    }
}

方案2:基于TemplatedParent的安全获取方式

如果你确定当前元素的TemplatedParent确实是ListBoxItem,可使用类型模式匹配做安全转换:

// 仅当TemplatedParent非空且类型为ListBoxItem时才会执行赋值
if (yourUiElement.TemplatedParent is ListBoxItem listBoxItem)
{
    var itemContent = listBoxItem.Content;
}

补充说明

如果你的ListBox做了数据绑定,ListBoxItem.Content的值就是你绑定的数据源单条实体,直接转换为对应的业务类即可使用,不需要额外解析。

内容的提问来源于stack exchange,提问作者Avrigeanu Laurian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:15:00