如何:在事件处理程序中查找源元素

此示例演示如何在事件处理程序中查找源元素。

示例

下面的示例演示在代码隐藏文件中声明的 Click 事件处理程序。 当用户单击处理程序附加到的按钮时,处理程序将更改属性值。 处理程序代码使用事件参数中报告的路由事件数据的 Source 属性来更改 Source 元素上的 Width 属性值。

<Button Click="HandleClick">Button 1</Button>
void HandleClick(object sender, RoutedEventArgs e)
{
    // You must cast the sender object as a Button element, or at least as FrameworkElement, to set Width
    Button srcButton = e.Source as Button;
    srcButton.Width = 200;
}
Private Sub HandleClick(ByVal sender As Object, ByVal e As RoutedEventArgs)
    'You must cast the object as a Button element, or at least as FrameworkElement, to set Width
    Dim srcButton As Button
    srcButton = CType(e.Source, Button)
    srcButton.Width = 200
End Sub

另请参阅