gpt4 book ai didi

WPF 如何将 mahapps 图标动态对象绑定(bind)到按钮模板样式

转载 作者:行者123 更新时间:2023-12-04 03:11:48 27 4
gpt4 key购买 nike

我想动态设置按钮的图标。当我使用 mahapps 图标时,我有这样的东西:

<Button x:Name="btnTest" Style="{StaticResource AppButton}" Content="Website" Tag="{iconPacks:PackIconMaterial Kind=Web}"/>

样式/模板是

<ControlTemplate TargetType="{x:Type Button}" >
<StackPanel Name="ButtonGrid" RenderTransformOrigin="0.5,0.5" DataContext="{Binding RelativeSource={RelativeSource AncestorType=Button}}">
<Rectangle Width="48" Height="48" Fill="{Binding Foreground}">
<Rectangle.OpacityMask>
<VisualBrush Stretch="Fill" Visual="{Binding Tag}" />
</Rectangle.OpacityMask>
</Rectangle>
<TextBlock Text="{Binding Path=Content, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}"/>
</StackPanel>
</Control.Template>

我通过这段代码通过 VB.NET 构建图标:

Private Sub ShowAppsTest()

Dim _style As Style = Me.FindResource("AppButton")

Test.Children.Clear()
For Each app As UserApplication In _user.applications

Dim btn As New MyApplicationButton(app.ApplicationName, app.ApplicationPath, app.ApplicationArgs, app.ApplicationIcon)
btn.Content = app.ApplicationName & "_test"
btn.Style = _style
Dim materialIcon As New PackIconSimpleIcons() With {.Kind = PackIconMaterialKind.Cube, .Width = 48, .Height = 48}
btn.Tag = materialIcon

AddHandler btn.Click, AddressOf launchApp

Test.Children.Add(btn)

Next

End Sub

但是以这种方式使用标签是行不通的(@mm8 在这篇文章 WPF binding mahapps metro icons in template 中建议使用静态版本)。如何将这些动态对象绑定(bind)到样式表?我应该使用转换器吗?或者还有其他更简单的方法吗?

谢谢。

最佳答案

如果稍微修改模板:

<ControlTemplate TargetType="{x:Type Button}" >
<StackPanel Name="ButtonGrid" RenderTransformOrigin="0.5,0.5" DataContext="{Binding RelativeSource={RelativeSource AncestorType=Button}}">
<Rectangle Width="48" Height="48" Fill="{Binding Foreground}">
<Rectangle.OpacityMask>
<VisualBrush Stretch="Fill">
<VisualBrush.Visual>
<iconPacks:PackIconMaterial Kind="{Binding Tag, RelativeSource={RelativeSource AncestorType=Button}}"
Width="24" Height="24" />
</VisualBrush.Visual>
</VisualBrush>
</Rectangle.OpacityMask>
</Rectangle>
<TextBlock Text="{Binding Path=Content, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}"/>
</StackPanel>
</ControlTemplate>

...您可以将 Tag 属性设置为枚举值:

<Button x:Name="btnTest" Style="{StaticResource AppButton}" Content="Website" Tag="{x:Static iconPacks:PackIconMaterialKind.Web}" />

Dim btn As New MyApplicationButton(app.ApplicationName, app.ApplicationPath, app.ApplicationArgs, app.ApplicationIcon)
...
btn.Tag = PackIconMaterialKind.Cube

关于WPF 如何将 mahapps 图标动态对象绑定(bind)到按钮模板样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44645929/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com