Home > Back-end >  WPF, c#, reference a specific UI element by its name
WPF, c#, reference a specific UI element by its name

Time:03-29

I have an application and I need to switch between multiple menus. My method for doing this is (as I've done before in Unity) is group all the elements of each menu into a Canvas GUI element, and using code to set which ones are visible and which are not. I'm just not sure how to reference the canvas itself in code (or the others, since I need multiple ones but I'm starting with one for now) in Visual Studio.

The only 'solution' I found (throws an error):

object mainCanvas = Canvas.Findname("Main_Menu");

CodePudding user response:

For a XAML based UI, the way to do this is to assign a name to the Canvas, and then it is accessible in the code-behind.

<Canvas x:Name="myCanvas"/>

Then in the code behind

void SomeEvent(object sender, RoutedEventArgs e)
{
    myCanvas...//Do whatever you were going to do with the canvas.
}
  • Related