Friday, August 7, 2009

Consider a scenerio , we have a listbox and some process where we have a tab navigation. On select of a tab, pass some inteeger value to a hidden textbox in the xaml . now based on the tab selected, we can switch the same listbox with different data template. This will avoid creating 2 listboxes in Silverlight 3 application.

the below code will explain in detail :

<ListBox x:Name="listbox1">

<ListBox.ItemTemplate>

<DataTemplate>

<ContentControl Content="{Binding}" Loaded="ContentControl_Loaded"/>

</DataTemplate>

</ListBox.ItemTemplate>

</ListBox>

<DataTemplate x:Key="datatemplate01">

<StackPanel>

<TextBlock Text="{Binding Name}"/>

<TextBlock Text="{Binding Dept}"/>

</StackPanel>

</DataTemplate>

<DataTemplate x:Key="datatemplate02">

<StackPanel>

<TextBlock Foreground="Blue" Text="{Binding Name}"/>

<TextBlock Foreground="Blue" Text="{Binding Address}"/>

</StackPanel>

</DataTemplate>

private void ContentControl_Loaded(object sender, RoutedEventArgs e)

{

ContentControl mycontentcontrol= (ContentControl)sender;

Data emp= (Data) mycontentcontrol.DataContext;

if (hiddentxt.Text ==1)

{

mycontentcontrol.ContentTemplate = (DataTemplate)this.Resources["datatemplate01"];

}

else if(hiddentxt.Text ==2)

{

mycontentcontrol.ContentTemplate = (DataTemplate)this.Resources["datatemplate01"];

}

}

How to link a storyboard to dynamically created button in silverlight 3.0

Consider , we have a storyboard in the MainPage.xaml in Silverlight 3 :

<UserControl.Resources>

<Storyboard x:Name="muthu">

<DoubleAnimation Storyboard.TargetName="mybutton" Storyboard.TargetProperty="Width" From="0"To="200"/>

</Storyboard>

</UserControl.Resources>


We can link that storyboard to a dynamically created button control like this :

string xaml = @"<Button xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"" x:Name=""mybutton""/>";

Button btn = (Button)XamlReader.Load(xaml);

this.LayoutRoot.Children.Add(mybutton);

Storyboard.SetTarget(this.sb.Children[0], mybutton);

this.sb.Begin();

Finding objects under control template at backend C# in Silverlight 3.0

<Button x:Name="muthu" >

<Button.Template>

<ControlTemplate TargetType="Button">

<Rectangle x:Name="baserect" Fill="Black" Loaded="baserect_Loaded"/>

</ControlTemplate>

</Button.Template>

</Button>



We can get in backend by :

private Rectangle baserect;

private void baserect_Loaded(object sender, RoutedEventArgs e)

{

this.baserect = (Rectangle)sender;

}