找到在WPF中引发MouseEvent的元素名称

时间:2014-04-14 07:24:25

标签: c# wpf

我有这样的XAML:

<Border x:Name="ModelWindowBorder" ClipToBounds="True" MouseWheel="Func">
</Border>

在代码背后:

private void Func(object sender, MouseWheelEventArgs e)
{
  // how can I get the element name that raised this event? (ie ModelWindowBorder)
}

2 个答案:

答案 0 :(得分:2)

您通过sender参数获取元素:

private void Func(object sender, MouseWheelEventArgs e)
{
    var element = (UIElement)sender;
}

如果您想获取其名称,可以转为FrameworkElement而不是UIElement并访问Name媒体资源:

private void Func(object sender, MouseWheelEventArgs e)
{
    var element = (FrameworkElement)sender;
    var name = element.Name;
}

答案 1 :(得分:1)

试试这个。

private void Func(object sender, MouseWheelEventArgs e)
{
   var name = (sender as Border).Name;
}