无法按类型找到模板化控件的父级(!)(wpf)
在我的 WPF 项目中,我有一些复杂的控制。在项目中,除了 MainWindow 之外,我只使用 Controls(它们都是模板化的)。
在一个屏幕上,我有以下布局(用于显示应用模板并填充内容后的布局):
MyScreenControl
-MyTableControl
--项目控制
--- HeaderItemsControl
-----HeaderItemsControl.Header
------MyHeaderControl
-----HeaderItemsControl.Items
------我的项目控件
------我的项目控件
------我的项目控件
...
当我在 ScreenControl 的代码文件中时,在 OnMouseLeftButtonDown 方法中,我想确定单击事件是来自 MyHeaderControl 还是 MyItemControl。
MouseButtonEventArgs 的 Source 是 ScreenControl,OriginalSource 是 MyItemControl/MyHeaderControl 模板中的 TextBlock。
我第一次尝试查找 MyItemControl/MyHeaderControl 是从 OriginalSource 开始并递归地查看 Parent 属性的类型。它工作正常,直到我到达模板的根(在本例中是 ViewBox),但根没有父元素。
我在我的早期项目中使用了类似的方法并且它有效,但后来我使用的是用户控件,而不是控件,也不是模板。
我应该如何解决这个问题有什么想法(好主意和代码一样受欢迎)?
谢谢, 天子
In my WPF project I have a bit complex control. In the project I only use Controls (they're all templated), besides MainWindow.
On one screen I have the following layout (for showing the layout after templates have been applied and contents filled):
MyScreenControl
-MyTableControl
--ItemsControl
--- HeaderItemsControl
-----HeaderItemsControl.Header
------MyHeaderControl
-----HeaderItemsControl.Items
------MyItemControl
------MyItemControl
------MyItemControl
...
When I'm in the ScreenControl's code file, in the OnMouseLeftButtonDown method I would like to determine if the click event came from a MyHeaderControl or a MyItemControl.
The MouseButtonEventArgs's Source is the ScreenControl and the OriginalSource is the TextBlock in the MyItemControl/MyHeaderControl 's template.
My first attempt to find the MyItemControl/MyHeaderControl was to start from the OriginalSource and recursively look at the type of the Parent property. It works fine till I get to the root of the Template (which is in this case a ViewBox), but the root has no Parent element.
I've used a method like this in az earlier project of mine and it worked, but then I was working with UserControls, not Controls, nor Templates.
Any ideas how should I approach this problem (a good idea is as wellcome as a code)?
thx,
Tenshiko
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否尝试过简单地获取 OriginalSource 的 templatedParent ? :(
请参阅:http://msdn.microsoft.com /en-gb/library/system.windows.frameworkelement.templatedparent.aspx)
Have you tried simply to get the originalSource's templatedParent ? :
(see: http://msdn.microsoft.com/en-gb/library/system.windows.frameworkelement.templatedparent.aspx)
查看 VisualTreeHelper.GetParent,其中将让您遍历可视化树,其中控件实际上已通过模板实例化。
Check out VisualTreeHelper.GetParent, which will let you walk the visual tree where the controls have actually been instantiated through the template.