唉,在 Windows 窗体中,它实际上就是一行。在 WPF 中,看起来会是几百个。
那是因为它是唯一可以放置在 winforms 按钮中的东西。
WPF 是一个真正的 UI 框架,而不是一些随机的半废弃的恐龙,只允许执行默认的操作(顺便说一句,这看起来很糟糕)。
选项 1:将图像放置为按钮的Content
:
如果您只想在按钮中放置图像,而不是其他任何东西,为什么不这样做呢?
<Style TargetType="Button">
<Setter Property="Background" Value="LimeGreen"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Background="{TemplateBinding Background}">
<ContentPresenter ContentSource="Content"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Then:
<Button>
<!-- Background not set, defaults to what's set in the Style -->
<Image Source="./ChessPieces/BlackKnight.png"/>
</Button>
<Button Background="Red">
<Image Source="./ChessPieces/BlackBishop.png"/>
</Button>
<Button Background="Blue">
<Image Source="./ChessPieces/BlackPawn.png"/>
</Button>
<!-- WPF's idea of "Dynamic" is not the same as win(hack)forms' -->
<Button Background="White">
<Image Source="{Binding SomeStringPropertyDefinedInAViewModel}"/>
</Button>
Result:
选项 2(不是很优雅):使用Tag
财产:
如果除了图像之外,您还想在按钮中放入其他内容,则可以采用一种有点老套的方法,将 ImageSource 放入按钮中Tag
财产。
<Style TargetType="Button">
<Setter Property="Background" Value="LimeGreen"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Background="{TemplateBinding Background}">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Tag, RelativeSource={RelativeSource TemplatedParent}}"
Height="50" Width="50"/>
<ContentPresenter ContentSource="Content"/>
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Then:
<Button Tag="./ChessPieces/BlackKnight.png"
Background="Blue"
Foreground="White"
Content="Some Text"/>
<Button Tag="./ChessPieces/BlackBishop.png"
Background="LightGray">
<CheckBox Content="A CheckBox!" VerticalAlignment="Center"/>
</Button>
Result:
选项 3:使用附属财产
与选项 2 相同,但使用在其他地方声明的属性,例如:
<Button ButtonImage.Source="./ChessPieces/BlackBishop.png"
<!-- etc -->
选项 4:创建自定义控件:
创建一个从 Button 派生的类(不带 XAML 的 .cs 文件)并添加DependencyProperty
保存图像,然后将模板设置为该图像并使用该值。
选项 5:MVVM
创建一个ButtonViewModel
,或者实际上使用委托命令在 ViewModel 中声明以绑定 Button 的属性。
不是一个选项:遍历可视化树并更改Image.Source
在代码中。
这不是你想做的事情。这根本不是一个好方法。
我可以永远继续下去,但我必须去睡觉。如果您希望我详细说明这些方法中的任何一种,请告诉我。