如何在 wpf 中设置按钮背景图像(如果为空)



我对WPF很陌生,我熟悉 vb.net 的WinForm,但现在我想学习WPF,我将项目设置为使用WPF,但在 vb.net 我使用它:

' checking if there is no background image in the button1
If IsNothing(butt1.BackgroundImage) Then
' then button1 appears
butt1.Visible = True
'and assign button2 background image to button1 background image since it is empty.
butt1.BackgroundImage = butt2.BackgroundImage
'assigning button2 background image to be empty
butt2.BackgroundImage = Nothing
'hiding button2
butt2.Visible = False

所以我使用 XAML 设计按钮,但我想在 Button1 单击事件中使用此代码,我也意识到 WPF 中的一切似乎都不同,我希望有人帮助我在 WPF 中实现这一目标。谢谢

在 WPF 中,Button有一个 Content 属性,您可以将其设置为string或任何元素(包括Image(:

button1.Content = new Image { Source = new BitmapImage(new Uri("Images/pic.png", UriKind.Relative)), Stretch = Stretch.Fill };

没有"背景"图像的概念。

BitmapImage的 Stretch 属性描述如何调整内容大小以填充其分配的空间。

最新更新