【问题标题】:How to set the background image to the dynamically created button control?如何将背景图片设置为动态创建的按钮控件?
【发布时间】:2011-06-23 06:44:53
【问题描述】:

我正在开发 windows phone 7 应用程序。我是 windows phone 7 应用程序的新手。我的应用程序中有列表框,我正在动态创建按钮控件并将它们添加到列表框控件中。现在我想为每个动态创建的按钮控件设置背景图像。我正在使用下面的代码来动态设置按钮控件的背景颜色

Button AlphabetButton = new Button();
                AlphabetButton.Background = new SolidColorBrush(Colors.Red);

以这种方式,而不是背景颜色,我想为我动态创建的按钮控件设置背景图像。这个怎么做 ?您能否提供我可以解决上述问题的任何代码或链接。如果我做错了什么,请指导我。

【问题讨论】:

    标签: silverlight button windows-phone-7 background-image dynamic


    【解决方案1】:

    试试这个:

        ImageBrush brush = new ImageBrush();
        brush.ImageSource = new BitmapImage(new Uri(@"Images/myImage.png", UriKind.Relative)); 
        AlphabetButton.Background = brush;
    

    另一种选择是使用按钮内容,例如:

       Uri uri = new Uri("/images/someImage.png", UriKind.Relative);  
       BitmapImage imgSource = new BitmapImage(uri);
       Image image = new Image();
       image.Source = imgSource;
       AlphabetButton.Content = image;
    

    小心图像构建操作。

    【讨论】:

      【解决方案2】:

      更好的方法是使用数据绑定...例如,您有一个要在列表框中显示的 Person 对象列表,在代码隐藏中将该列表设置为 ItemsSource:

      public class Person()
      {
        public string Name {get; set;}
      }
      
      var persons = new List<Person>();
      // ... add some person objects here ...
      listBox.ItemsSource = persons
      

      在您的 XAML 中,您可以提供一个 DataTemplate,将每个人呈现为一个按钮:

      <ListBox x:Name="listBox">
        <Listox.ItemTemplate>
           <DataTemplate>
              <Button Content={Binding Path=Name}/>
           </DataTemplate>
        </Listox.ItemTemplate>
      </ListBox>
      

      这将呈现一个显示每个人姓名的按钮列表。

      要为每个按钮指定图像,请扩展按钮的内容以包含图像:

      <ListBox x:Name="listBox">
        <Listox.ItemTemplate>
           <DataTemplate>
              <Button>
                <StackPanel Orientation="Horizontal">
                   <TextBlock Text="{Binding Path=Name}"/>
                   <ImageText Source="{Binding Path=Image}"/>
                </StackPanel>
              </Button>
           </DataTemplate>
        </Listox.ItemTemplate>
      </ListBox>
      

      您当然必须将 ImageSource 属性添加到您的 Person 对象:

      public class Person()
      {
        public string Name {get; set;}
        public ImageSource Image {get; set;}
      }
      

      另一种方法是使用值转换器将 Person 的某些属性转换为图像:

      Dynamic image source binding in silverlight

      如果您不想使用绑定(我个人认为这是最好的方法),您可以创建一个具有 ImageSource 属性的 Button 子类,如下所示:

      Creating an image+text button with a control template?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-31
        • 2015-10-27
        • 1970-01-01
        • 2015-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多