问题描述
Private Sub MakeButton(sp As StackPanel, sStr As String)
Dim btn As New Button()
Dim sp1 As New StackPanel()
Dim img As System.Drawing.Bitmap
img = My.Resources.FldrClose
sp1.Orientation = Orientation.Horizontal
'Wrong
sp1.Children.Add(New Image With {.Source = img})
'sp1.Children.Add(New Image With {.Source = New BitmapImage(New Uri("c:\tmp\FldrOpen.png")),
' .Width = 100,
' .HorizontalAlignment = Windows.HorizontalAlignment.Left})
sp1.Children.Add(New TextBlock With {.Text = sStr,
.Width = 100,
.HorizontalAlignment = Windows.HorizontalAlignment.Right})
btn.Height = 30
btn.Width = 200
btn.Content = sp1
sp.Children.Add(btn)
End Sub
在参考资料中,我有几个png文件。这个png文件我要添加到我的按钮。
In Resources I have several "png" files. This "png" files I want to add to my buttons.
推荐答案
<button>
<grid>
<grid.rowdefinitions>
<rowdefinition />
<rowdefinition />
</grid.rowdefinitions>
<image grid.row="1" x:name="ImagePlaceHolder" xmlns:x="#unknown" />
<textblock grid.row="2" x:name="TextPlaceHolder" xmlns:x="#unknown" />
</grid>
</button>
然后你可以在运行时引用这些控件。
然而,更好的解决方案是拥有两个数据类
Then you could refer to those controls at runtime.
However, a better solution would be to have two dataclasses
ButtonContentWithImage
ButtonContentWithoutImage
然后将按钮的datacontext设置为其中一个类,并在WPF窗口/控件/页面的资源中使用Datatemplates来正确显示它们。
阅读其中一些链接:
[]
[]
[]
Then set the datacontext of the button to one of those classes and use Datatemplates in the resources of the WPF window/control/page to display them properly.
Have a read on some of these links:
http://stackoverflow.com/questions/1933127/creating-an-imagetext-button-with-a-control-template[^]
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/1f4b6cf8-fe34-43be-bef7-e01c2a4f1b04[^]
http://wpftutorial.net/DataTemplates.html[^]
这篇关于添加资源“png”文件到按钮图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!