如何给动态创建的按钮控件设置背景图片?
我正在开发 Windows Phone 7 应用程序。我是 Windows Phone 7 应用程序的新手。我的应用程序中有列表框 &我动态创建按钮控件并将它们添加到列表框控件。现在我想为每个动态创建的按钮控件设置背景图像。我使用以下代码动态设置按钮控件的背景颜色
Button AlphabetButton = new Button();
AlphabetButton.Background = new SolidColorBrush(Colors.Red);
通过这种方式,我想为动态创建的按钮控件设置背景图像,而不是背景颜色。如何做到这一点?您能否提供任何代码或链接来解决上述问题。如果我做错了什么,请指导我。
I am developing window phone 7 application. I am new to the window phone 7 application. I have Listbox in my application & I am dynamically creating the button control and adding them to the listbox control. Now I want to set the background image for each dynamically created button control. I am using the following code to dynamically set the background color of button control
Button AlphabetButton = new Button();
AlphabetButton.Background = new SolidColorBrush(Colors.Red);
In this way instead of background color I want to set the background image for my dynamically created button control. How to do this ? Can you please provide me any code or link through which I can resolve the above issue. If I am doing anything wrong then please guide me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
另一种选择是使用按钮内容,例如:
小心图像构建操作。
Try this:
Another option is to use the Button Content like for example:
Be careful with the image Build Action.
更好的方法是使用数据绑定...例如,您有一个要在列表框中显示的 Person 对象列表,在代码隐藏中将该列表设置为 ItemsSource:
然后在 XAML 中您可以提供一个 DataTemplate将每个人呈现为一个按钮:
这将呈现一个显示每个人姓名的按钮列表。
要为每个按钮指定图像,请扩展按钮的内容以包含图像:
当然,您必须向 Person 对象添加 ImageSource 属性:
另一种选择是使用值转换器将 Person 的某些属性转换为image:
silverlight 中的动态图像源绑定
如果您不想使用绑定(我个人认为这是最好的方法)您可以创建一个具有 ImageSource 属性的 Button 子类,如下所示:
使用控件模板创建图像+文本按钮?
A much better approach would be to use databinding ... say for example you have a list of Person objects that you want to display in your listbox, in codebehind set the list as the ItemsSource:
In you XAML you can then supply a DataTemplate that renders each person as a Button:
This will render a list of Buttons which display the name of each person.
To specify an image for each button extend the content of your button to include an image:
You will of course have to add an ImageSource property to your Person object:
Another alternative is to use a value converter to convert some property of your Person into an image:
Dynamic image source binding in silverlight
If you do not want to use binding (which I personally think is the best approach) you could create a Button subclass that has an ImageSource property as per the following:
Creating an image+text button with a control template?