I have a small WPF application, which has a Canvas and a Grid. I placed some custom user controls on the Grid. Now I would like to capture some mouse events on them. As a consequence of one event I would like to add (or modify) something to the canvas. However in the user control, you don’t have a reference to the underlying canvas. First question, is there a way to get this reference, for example like getElementById(..) in JavaScript.
Also I know that you should avoid such references, if you want a clean architecture. In this case, whats a good practice to catch events at a specific user control and then to be able to invoke something on another object.
You do have access to the Canvas, Grid or any other element in your UserControl. The easiest way yo access them is to make sure each one has a name which is done by using the x:Name attribute.
Then within your UserControl you can access it with myGrid. To access a Grid from outside the UserControl you would need to create a method in your UserControl that allowed you to manipulate it.
There is a this.FindName method you can use in a UserControl which is the equivalent of javascript’s getElementById but you shouldn’t need to use it given you can access objects directly with their name.