【问题标题】:Silverlight ImageButton UserControlSilverlight ImageButton 用户控件
【发布时间】:2023-03-30 10:26:01
【问题描述】:

我刚开始使用 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);
    }

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

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

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

感谢您的帮助

【问题讨论】:

    标签: silverlight user-controls silverlight-2-rc0


    【解决方案1】:

    您可以通过模板化一个普通按钮轻松获得 ImageButton,因此您根本不需要 UserControl。假设 Button.Content 将是 ImageSource。按钮的 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}"/>
    

    【讨论】:

    • hmm...它已经有宽度和高度,我认为它与DataContext有关...
    • 这种用法会产生一个带有图像的按钮。我想要一个可点击的图像(没有默认按钮在视觉上封装它)....我相信我上面的代码完全用图像覆盖了默认按钮模板。
    • 不,这正是您想要的。它不会显示按钮镶边,请尝试一下。
    • 您刚刚更改了响应,您现在拥有的内容将覆盖模板
    • 但是……我有多个图像……我得到一个 URL 列表,从中构造图像对象……然后使用我刚刚创建的图像创建上述用户控件,然后添加他们到一个包装面板
    【解决方案2】:

    我相信这会有所帮助。它对我有用!

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

    使用 ImageSource 代替 Image。例如。 typeof(ImageSource) 等。

    【讨论】:

      猜你喜欢
      • 2014-04-07
      • 2010-10-31
      • 2010-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多