WPF FrameworkElement鼠标点击问题
在 WPF 应用程序中,我在网格内有一堆自定义控件。为了处理鼠标单击它们,我使用网格的 MouseLeftButtonDown
事件,并在事件处理程序中检查单击了哪个 CustomControl:
private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
FrameworkElement feSourceComm = e.Source as FrameworkElement;
MyCustomControl SCurrentComm = new MyCustomControl();
try
{
SCurrentComm = (MyCustomControl)feSourceComm;
}
catch (Exception)
{
...
当我将所有 CustomControl 放入 UserControl 中,然后放入网格中时,出现了问题。在这种情况下,该方法不起作用。
我通过 e.Source.GetType().ToString(); 检查了每种情况下的点击源类型,并得到以下结果:
当没有问题时(如果我将 CustomControls在没有 UserControl 的网格中)
MyProjectNamespace.MyCustomControl
当我将 CustomControls 放入 UserControl,然后放入网格时
MyProjectNamespace.UserControls.MyUserControlName
当我将 CustomControls 放入 UserControl,然后放入网格并通过 XamlReader.Load 从外部文件加载 UserControl
System.Windows.Controls.UserControl
那么,我的问题:
当 CustomControls 位于 UserControl 内部时,如何使它们可视为 e.Source
?
In a WPF app I have I bunch of CustomControls inside a Grid. For processing Mouse clicks on them I use the MouseLeftButtonDown
event of the Grid and in the event handler I check which CustomControl was clicked:
private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
FrameworkElement feSourceComm = e.Source as FrameworkElement;
MyCustomControl SCurrentComm = new MyCustomControl();
try
{
SCurrentComm = (MyCustomControl)feSourceComm;
}
catch (Exception)
{
...
The problem appeared when I placed all CustomControls in a UserControl and then inside the Grid. In this case approach doesn't work.
I checked the type of click source in each case by e.Source.GetType().ToString();
and get the following results:
When there are no problem (in case I put CustomControls in the Grid without UserControl)
MyProjectNamespace.MyCustomControl
When I put CustomControls in the UserControl and then in the Grid
MyProjectNamespace.UserControls.MyUserControlName
When I put CustomControls in the UserControl and then in the Grid and load the UserControl from external file by XamlReader.Load
System.Windows.Controls.UserControl
So, my question:
How to make CustomControls vizible as e.Source
when they are inside of a UserControl?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
e.OriginalSource
将告诉您点击发生在哪个特定元素上。如果这不是您的自定义控件,请沿着OriginalSource
的父链向上查找,直到找到您的自定义控件e.OriginalSource
will tell you which specific element the click happened on. if that is not your customcontrol, walk up the Parent chain of theOriginalSource
until you find your customcontrol