如何从 DataTemplate 获取 Control 到 ControlTemplate ? [英] How to get Control from DataTemplate to ControlTemplate ?

查看:17
本文介绍了如何从 DataTemplate 获取 Control 到 ControlTemplate ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<ListBox>
   <ListBox.ItemTemplate>
      <DataTemplate>
        <Button Content="Click Me"
                Click="OnClick"
                Name="btn"/>
      </DataTemplate>
   </ListBox.ItemTemplate></ListBox>

我想在单击按钮时获取相关的 ListBoxItem.如何执行此操作?

I want to get relevant ListBoxItem when I Click the Button.how to do this ?

private void OnClick(object sender, RoutedEventArgs e){// How to get ListBoxItem?}

推荐答案

您可以使用 Linq-to-VisualTree 如下:

Button btn = sender as Button;
ListBoxItem item = btn.Ancestors<ListBoxItem>().Cast<ListBoxItem>().First();

这将查找所需类型的按钮的第一个祖先.

This finds the first ancestor of the button that is of the desired type.

作为替代方案,如果您使用数据绑定,您可以检查 Button 继承的 DataContext 以查看它绑定到哪个模型项.那将是我的首选.

As an alternative, if you are using databinding, you could inspect the inherited DataContext of the Button to see which model item it is bound to. That would be my first preference.

这篇关于如何从 DataTemplate 获取 Control 到 ControlTemplate ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆