[英]controlling multiple grids visibility
I have a WPF application. 我有一个WPF应用程序。 It contains quite a few grids.
它包含许多网格。 I am using (trying to) the MVVM pattern.
我正在使用(尝试使用)MVVM模式。
So in my view model I have properties of System.Windows.Visibility to control if a grid is visible or collapsed. 因此,在我的视图模型中,我具有System.Windows.Visibility属性,可以控制网格是可见的还是折叠的。 This all works fine.
这一切都很好。
However say I have 50 grids for example. 但是说我有50个网格。 I only want one to be visible at a time.
我只希望一次可见。 So say the application on start up shows grid1.
因此,可以说启动时的应用程序显示grid1。 A user then clicks a button which means grid2 should now be visible and grid1 should collapse.
然后,用户单击一个按钮,这意味着grid2现在应该可见,并且grid1应该折叠。
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: 您可以使用将所选网格ID转换为可见性的转换器,如下所示:
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}/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.