Monday, 5 July 2010

Dynamically change UI Element in Silverlight

I ran into a situation where, based on what grid client wants to see, I need to show them that particular grid of user’s choice. The catch here is that, all the grids are different third party controls so I can not generalize and create one view, instead each grid will be separate view. Here is how I went about doing it. I have main page XAML, which has a combo box which will allow the user to select which grid they want to see. By default, we show the first grid on load. When the grid selection changes I need to replace the current grid with selected grid.

Following is main page XAML.

<Grid x:Name="LayoutRoot" Background="White">
        <RowDefinition Height="5*"/>
        <RowDefinition Height="95*" />

    <ComboBox Name="comboSelection" SelectionChanged="comboSelection_SelectionChanged" Width="300" HorizontalAlignment="Left" Grid.Row="0">
        <ComboBoxItem Content="First" IsSelected="True"/>
        <ComboBoxItem Content="Second"/>
        <ComboBoxItem Content="Third"/>
    <sdk:DataGrid AutoGenerateColumns="False" Grid.Row="1" HorizontalAlignment="Left" Margin="0,0,0,0" Name="dataGrid1" VerticalAlignment="Top" />

Now I create two other XAML with data grid in it call it First and Second. A Sample First XAML looks like this

<Grid x:Name="LayoutRoot" Background="White">
        <sdk:DataGrid AutoGenerateColumns="True" HorizontalAlignment="Left" Name="dataGrid2" VerticalAlignment="Top" />

in the code behind, I load some data and data bind it to datagrid2. The interesting part of the code which replaces the default grid from the main page is as follow

FirstControl first = new FirstControl();
Grid.SetRow(first, 1);

So create the first grid and remove the existing grid from row 1, add the newly created as a child to the Layout Root. Make sure you set which row the newly added grid has to go to. That’s it. Now you can switch in and out of grid as you want.


Post a Comment