In one of my applications I need to allow the user to customize the user interface in certain ways. To do so, I'm allowing the user to specify the user interface in XAML, which I load dynamically when the application is started. This works fine.
Now I want to provide custom control to the user, which is derived from Border
(let's call it MyFrame
).
I need to make sure that MyFrame
may not be child of another MyFrame
, so the following should be prevented:
<ns:MyFrame>
<Grid>
<ns:MyFrame />
</Grid>
</ns:MyFrame>
How should I implement this?
You won't be able to do this at compile time.
However, at runtime, you can check whenever a new instance of MyFrame is created, if it has a parent MyFrame, using this visual tree walker . If it does, raise an exception.
I would throw an exception with a clear message from the Loaded event handler on MyFrame: step through the ancestors of the new MyFrame instance and try to find another one; if you do find one, throw the exception.
Alternative: use an inheritable attached property that you set on all instances of MyFrame - and check that in the Loaded handler.
I can't imagine any way to enforce your rule in a static manner.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.