如何将TemplatedParent的Content属性正确赋值给变量?
错误原因
你的报错核心是两点:
- 没有对
TemplatedParent做空校验和类型安全转换,直接强制转换会在类型不匹配/对象为空时抛出无效转换/空引用异常 - 如果点击事件的触发源是
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
相关产品推荐
相关产品推荐

