user2509714
user2509714

Reputation: 33

Accessing xaml elements from code if I have their string name

I have a code in wich i need to be able to access to a different amount of prebuilt grids in XAMl and make them visible or collapsed

All grid are named like grid1,grid2,grid3 etc. I have the ability in code to obtain the string name via a random number and get the name od the grid i'd like to show.

I searched online and people suggest to use the reflect method, but i'm having a hard time trying to figure out the syntax that i have to use.

Best regards

Upvotes: 2

Views: 7604

Answers (1)

Sheridan
Sheridan

Reputation: 69987

The most straight forward way of doing this is to just declare a Name value for each Grid...:

<Grid Name="Grid1">
    ...
</Grid>

... and then you can access them by that name from the code behind:

Grid1.Visibility = Visibility.Hidden;

However, this is WPF and that is generally not recommended. A preferred method would be to add some bool properties to your code behind or view model...:

public bool IsGrid1Visible { get; set; } // Implement INotifyPropertyChanged interface

... and then to bind these directly to the Grid1.Visibility property using a BooleanToVisibilityConverter:

<Grid Grid1.Visibility="{Binding IsGrid1Visible, Converter={StaticResource 
    BooleanToVisibilityConverter}}">
    ...
</Grid>

Then you can change the Grid.Visibility value by simply setting the IsGrid1Visible property to true or false.

Upvotes: 2

Related Questions