C# wpf画布获取子名称
我有一张帆布和一些孩子C# wpf画布获取子名称,c#,wpf,xaml,canvas,C#,Wpf,Xaml,Canvas,我有一张帆布和一些孩子 <Canvas Name="Canvas" MouseDown="getElements"> <Rectangle Height="200" Width="200" Name="Element1"/> <Rectangle Height="200" Width="200" Name="Element2"/> </Canvas> 但我只知道画布的名字。有人能帮我找到被点击元素的名称吗 提前谢谢 事件从画布
<Canvas Name="Canvas" MouseDown="getElements">
<Rectangle Height="200" Width="200" Name="Element1"/>
<Rectangle Height="200" Width="200" Name="Element2"/>
</Canvas>
但我只知道画布的名字。有人能帮我找到被点击元素的名称吗
提前谢谢 事件从画布中的元素路由。要获取原始源,可以改用RoutedEventArgs:
public void getElements(object Sender, RoutedEventArgs e)
{
DependencyObject dpobj = e.OriginalSource as DependencyObject;
string name = dpobj.GetValue(FrameworkContentElement.NameProperty) as string;
Console.WriteLine("Element Clicked: " + name);
}
由于
MouseDown
是路由事件,而不是EventArgs
使用RoutedEventArgs
或MouseDown
可以使用MouseButtonEventArgs
。它将为您提供OriginalSource
属性,您可以尝试获取e.OriginalSource
的Name
:
private void getElements(object sender, MouseButtonEventArgs e)
{
var elementName = (e.OriginalSource as FrameworkElement).Name;
}
您可以在画布上为MouseLeftButtonUp事件创建一个事件处理程序(由于WPF使用路由事件,该事件将“冒泡”到父级,并且也将在那里引发)。XAML代码看起来有点像这样:
<Window x:Class="CanvasChildren.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Canvas MouseLeftButtonUp="UIElement_OnMouseLeftButtonUp">
<Rectangle Canvas.Top="10" Canvas.Left="10" Height="200" Width="200" Name="Element1" Fill="LightBlue"/>
<Rectangle Canvas.Left="250" Canvas.Top="100" Height="200" Width="200" Name="Element2" Fill="DarkSalmon"/>
</Canvas>
</Window>
您可以下载我的完整示例(这是一个Dropbox链接)
<Window x:Class="CanvasChildren.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Canvas MouseLeftButtonUp="UIElement_OnMouseLeftButtonUp">
<Rectangle Canvas.Top="10" Canvas.Left="10" Height="200" Width="200" Name="Element1" Fill="LightBlue"/>
<Rectangle Canvas.Left="250" Canvas.Top="100" Height="200" Width="200" Name="Element2" Fill="DarkSalmon"/>
</Canvas>
</Window>
private void UIElement_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
var rectangle = (Rectangle) e.Source;
var name = rectangle.Name;
}