微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Silverlight ImageButton UserControl

我刚刚开始使用Silverlight(2 RC0)并且似乎无法使用以下内容.我想创建一个简单的图像按钮用户控件.

我的用户控件的xaml如下:

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

背后的代码如下:

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);
    }

我希望能够动态创建ImageButtons并将它们填充到像WrapPanel这样的容器中:
假设我们已经有一个名为“image”的图像:

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

我需要做什么才能显示图像?我假设我需要对DataContext做一些事情,但我不太清楚什么或在哪里.

谢谢你的帮助

解决方法

您可以通过模板化普通Button轻松获得ImageButton,这样您根本不需要UserControl.假设Button.Content将是ImageSource. Button的ControlTemplate将是:

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

作为ItemsControl使用URL集合作为其ItemsSource,您可以添加WrapPanel作为ItemPanel.如果您没有指定,则认为StackPanel.

<DataTemplate x:Key="dataTemplate">
  <Button Template="{StaticResource btn_template}" Content="{Binding}"/>
</DataTemplate>    


 <ItemsControl ItemsSource="{Binding UrlCollection}" Itemstemplate="{StaticResource dataTemplate}"/>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐