Silverlight ImageButton UserControl

I am just starting out with Silverlight (2 RC0) and it doesn't seem to work. I want to create a custom control for a simple image.

My xaml for the user control is as follows:

<Button> <Button.Template> <ControlTemplate> <Image Source="{TemplateBinding ImageSource}" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" /> </ControlTemplate> </Button.Template> </Button> 

The code is as follows:

 public partial class ImageButtonUserControl : UserControl { public ImageButtonUserControl() { InitializeComponent(); } public Image Source { get { return base.GetValue(SourceProperty) as Image; } set { base.SetValue(SourceProperty, value); } } public static readonly DependencyProperty SourceProperty = DependencyProperty.Register("SourceProperty", typeof(Image), typeof(ImageButtonUserControl),null); } 

I want to be able to dynamically create ImageButtons and add them to a container, for example WrapPanel: Suppose we already have an image named "image":

 ImageButtonUserControl imageButton = new ImageButtonUserControl(); imageButton.Source = image; this.thumbnailStackPanel.Children.Add(imageButton); 

What do I need to do to display the image? I suppose I need to do something with the DataContext, but I'm not quite sure what and where.

Thanks for any help

+6
silverlight user-controls
source share
2 answers

You can easily get an ImageButton by simply setting up a regular button template so you don't need a UserControl at all. Assuming Button.Content will be an ImageSource. ControlTemplate buttons will be:

  <ControlTemplate x:Key="btn_template"> <Image Source="{TemplateBinding Content}" /> </ControlTemplate> 

And using as an ItemsControl element with a collection of URLs as an ItemsSource element, you can add a WrapPanel as an ItemPanel. The default will be a StackPanel if you do not specify it.

 <DataTemplate x:Key="dataTemplate"> <Button Template="{StaticResource btn_template}" Content="{Binding}"/> </DataTemplate> <ItemsControl ItemsSource="{Binding UrlCollection}" ItemsTemplate="{StaticResource dataTemplate}"/> 
+10
source share

I think this will help. It was for me!

http://www.nikhilk.net/Silverlight-Effects-In-Depth.aspx

Use ImageSource instead of image. EG. typeof (ImageSource) etc.

+2
source share

All Articles