【问题标题】:How to find clicked UIElement child如何找到点击的 UIElement 孩子
【发布时间】:2014-07-12 23:07:40
【问题描述】:

我想获取点击的 UIElement 的子元素,即按钮。也许有一个简单而简短的解决方案?我已经搜索了一段时间,但找不到易于理解和使用的解决方案。我将不胜感激与此问题相关的任何帮助。

我现在拥有的代码:

private new void MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{

    if (sender == (sender as UIElement))
    {

        //TODO: getting controls name that is placed inside clicked UIElement

    }

}

编辑:

想提一下 UIElement 是使用 ResourceDictionary 模板的 ContentControl。 我的 xaml 代码看起来像这样

 <ContentControl Style="{StaticResource DesignerItemStyle}">
        <Button x:Name="btnAdd" Content="add function" IsHitTestVisible="True" 
        HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
</ContentControl>

【问题讨论】:

  • 这取决于你在这里指的是什么 UIElement,例如如果那个 UIElement 是事件的所有者MouseLeftButtonDown 与处理程序相关联,你可以使用sendere.Source,否则您可能需要查看e.OriginalSource

标签: wpf uielement


【解决方案1】:

MouseButtonEventArgs 中有两个属性可以用于此目的

Source

此属性包含对引发事件的对象的引用。示例按钮等

OriginalSource

由纯命中测试确定的原始报告源,在父类进行任何可能的Source 调整之前,这可能是为了展平复合元素树。例如 Rectangle、Border 或 Button 内的任何模板元素。

您可以通过casting OriginalSourceFrameworkElement 或更合适的方式检索元素的Name

如果 OriginalSource 不是所需的元素,那么您可以检索 OriginalSource 的逻辑父级,这更有可能是所需的元素,并且检索名称与上述保持相同。

检索逻辑父示例

LogicalTreeHelper.GetParent(e.OriginalSource as DependencyObject);

【讨论】:

  • 感谢您的回答@pushpraj。我将您提供的这行代码更改为类似的内容,并且有效! - var childControl = LogicalTreeHelper.GetChildren(e.Source as DependencyObject); 然后获取刚刚使用 foreach 循环的子控件名称。太好了!
  • 我刚刚意识到这个方法只返回该子元素的内容而不是名称或其他属性。此外,当我转换为 FrameworkElement 时,e.OriginalSource 也无法获取除 Content 之外的其他属性。
  • 您可以定义一个策略来强制转换为Panel 以获取其子级或ContentControl 以获取它的内容,具体取决于对象的类型或其他需要的合适类型。 FrameworkElement 是一个非常基本的例子,它有助于获得 Name 属性。您可以发布您的应用程序的工作示例。看后能不能推荐一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-02
  • 1970-01-01
  • 2018-02-12
  • 2016-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多