kurakura88 kurakura88 - 23 days ago 27
C# Question

Multiple Views approach in WPF

Similar to Windows Explorer, I have a list of folders as data, but I want to have multiple views, for ex: icon view, list view, etc.

This is my approach:

<Page.Resources>
<DataTemplate x:Name="iconViewDataTemplate"> ... </DataTemplate>
<DataTemplate x:Name="listViewDataTemplate> ... </DataTemplate>
</Page.Resources>

<Grid>
<StackPanel>
<Grid>
<Button x:Name="toggleViewButton" Content="Toggle View" Click="toggleViewButton_Click" />
</Grid>
<Grid>
<GridView x:Name="folderView"
ItemsSource="{Binding Path=folders}"
ItemTemplate="{StaticResource iconViewDataTemplate}"/>
<ListView x:Name="listView"
ItemsSource="{Binding Path=folders}"
ItemTemplate="{StaticResource listViewDataTemplate}"
IsEnabled="False"
Opacity="0"/>
</Grid>
</StackPanel>
</Grid>


in the code behind

private void toggleViewButton_Click(object sender, RoutedEventArgs e)
{
folderView.IsEnabled = folderView.IsEnabled ^ true;
folderView.Opacity = folderView.Opacity ^ 1;
listView.IsEnabled = listView.IsEnabled ^ true;
listView.Opacity = listView.Opacity ^ 1;
}



  1. Is this the right approach? I am concerned that if I have a lot of views, then toggling is not easy, because I have to track each view's state.

  2. What is the best practice to implement this multiple views?

  3. Can I have something like an interface for the view, then I can change the style:



for ex:

<IView x:Name="mainView"
Style="{Binding istyle}"
ItemsSource="{Binding Path=folders}"
ItemTemplate="{Binding istyle.Template}" />


Then toggling can be done simply by changing the style in the istyle.

Answer

The solution I picked is to use <Frame> where I can change the Frame with proper View I need.

<Grid>
  <StackPanel>
    <Grid>
      <Button x:Name="toggleViewButton" Content="Toggle View" Command="{Binding ToggleCommand}" />
    </Grid> 
    <Grid>
       <Frame x:Name="viewFrame"/>
    </Grid>
  </StackPanel>
</Grid>

Then in The ViewModel' ToggleCommand, I would make the Frame to navigate to new View.

Comments