I am just starting out with Silverlight (2 RC0) and can’t seem to get the following to work. I want to create a simple image button user control.
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 behind 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 the ImageButtons and stuff them in a container like a WrapPanel: Assume we have an image named “image” already:
ImageButtonUserControl imageButton = new ImageButtonUserControl();
imageButton.Source = image;
this.thumbnailStackPanel.Children.Add(imageButton);
What do I need to do to get the image to display? I'm assuming I need to do something with DataContext, but I'm not quite sure what or where.
Thanks for any help
You can get an ImageButton easily just by templating an ordinary Button so you dont require a UserControl at all. Assuming that Button.Content will be the ImageSource. The ControlTemplate of the Button will be:
<ControlTemplate x:Key="btn_template">
<Image Source="{TemplateBinding Content}" />
</ControlTemplate>
And the usage as an ItemsControl with URL collection as its ItemsSource, You can add WrapPanel as the ItemPanel. Default will be StackPanel if you don't specify one.
<DataTemplate x:Key="dataTemplate">
<Button Template="{StaticResource btn_template}" Content="{Binding}"/>
</DataTemplate>
<ItemsControl ItemsSource="{Binding UrlCollection}" ItemsTemplate="{StaticResource dataTemplate}"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With