2

我正在开发window phone 7应用程序。我不熟悉window phone 7应用程序。我有我的应用程序中的列表框&我动态创建按钮控件并将它们添加到列表框控件。现在我想为每个动态创建的按钮控件设置背景图像。我使用下面的代码,以动态地设置按钮控制如何将背景图像设置为动态创建的按钮控件?

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

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

回答

6

试试这个:

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; 

请注意图像构建操作。

0

更好的方法是使用数据绑定......比方说你有,你想在你的列表框中显示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;} 
} 

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

Dynamic image source binding in silverlight

如果你不想使用绑定(我个人认为是最好的方法),你可以创建一个具有一个ImageSource的财产按下列一个按钮子类:

Creating an image+text button with a control template?

相关问题