I have a WPF application. It contains quite a few grids. I am using (trying to) the MVVM pattern.
So in my view model I have properties of System.Windows.Visibility to control if a grid is visible or collapsed. This all works fine.
However say I have 50 grids for example. I only want one to be visible at a time. So say the application on start up shows grid1. A user then clicks a button which means grid2 should now be visible and grid1 should collapse.
I can do this with the below code although I feel this is a poor way of doing it as it is not very scale able
void GridSelector(string gridName)
{
if(gridName == "grid1")
{
Grid1 = Visibility.Visible;
Grid2 = Visibility.Collapsed;
Grid3 = Visibility.Collapsed;
...
Grid50 = Visibility.Collapsed;
}
else if(gridName == "grid2")
{
Grid1 = Visibility.Collapsed;
Grid2 = Visibility.Visible;
Grid3 = Visibility.Collapsed;
...
Grid50 = Visibility.Collapsed;
}
...
}
What is a better way of doing this? Is this where I should use reflection?
You could use a converter that converts the selected grid id to a visibility, like so:
public class GridIdToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
return value.ToString() == parameter.ToString() ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
And apply it to your grids
<Grid Visibility="{Binding SelectedGridId, Converter={StaticResource GridIdToVisibilityConverter}, ConverterParameter=grid1}/>
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.