Wednesday, November 19, 2008

MSDN Question on WPF: MDI like WPF Window

Well, MDI are not supported in WPF and this is not a hack to create MDI applications in WPF. What we will be doing is to simulate MDI like behavior. The main window has two buttons one for Screen1 and another for Screen2. The XAML is shown below.

   1: <Grid>  


   2:         <Grid.RowDefinitions>  


   3:             <RowDefinition Height="40*" />  


   4:             <RowDefinition Height="222*" />  


   5:         </Grid.RowDefinitions>  


   6:         <StackPanel Grid.Row="0" Orientation="Horizontal">  


   7:             <Button Width="Auto" Click="Screen1_Click">Screen 1</Button>  


   8:             <Button Width="Auto" Click="Screen2_Click">Screen 2</Button>  


   9:         </StackPanel>  


  10:         <ContentPresenter Grid.Row="1" Name="ScreenHolder"></ContentPresenter>  


  11: </Grid>  



The Code Behind for the XAML is.



   1: Screen1 sc1 = new Screen1();  


   2: Screen2 sc2 = new Screen2();  


   3: private void Screen1_Click(object sender, RoutedEventArgs e)  


   4: {  


   5:     ScreenHolder.Content = sc1;  


   6: }  


   7:   


   8: private void Screen2_Click(object sender, RoutedEventArgs e)  


   9: {  


  10:     ScreenHolder.Content = sc2;  


  11: }  



Screen1 and Screen2 are User Controls whose XAML is shown below.



   1: <UserControl x:Class="MSDNSocial.Screen1"  


   2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  


   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">  


   4:     <Grid>  


   5:         <Label VerticalAlignment="Center" FontSize="20" HorizontalAlignment="Center">  


   6:             This is Screen 1  


   7:         </Label>  


   8:     </Grid>  


   9: </UserControl>  


  10: <!-- User control 2 -->


  11: <UserControl x:Class="MSDNSocial.Screen2"  


  12:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  


  13:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">  


  14:     <Grid>  


  15:         <Label VerticalAlignment="Center" FontSize="20" HorizontalAlignment="Center">  


  16:             This is Screen 2  


  17:         </Label>  


  18:     </Grid>  


  19: </UserControl>  



When you click Screen1 button, screen1 appears and clicking screen2 shows screen2. Note that it is the same User Control that will be showed again and again. So the state should be essentially saved. Much like Page Navigation without crying out loud.

1 comment:

Anonymous said...

Good try, But this is not the way MDI is suppose to work.