【发布时间】:2017-12-06 08:12:56
【问题描述】:
在 WPF 项目中,使用以下代码在 Window_Loaded 事件中自定义按钮:
Dim style As Style = New Style
style.TargetType = GetType(Button)
Dim trigger As DataTrigger = New DataTrigger
trigger.Value = "OK"
'set binding
Dim bi As New Binding
Dim pp As New PropertyPath("Content")
bi.Path = pp
bi.RelativeSource = RelativeSource.Self
trigger.Binding = bi ' New Binding(pp.Path)
Dim setter As Setter = New Setter
setter.Property = Button.BackgroundProperty
setter.Value = Brushes.Red
trigger.Setters.Add(setter)
'clear the triggers
style.Triggers.Clear()
style.Triggers.Add(trigger)
btn_Step.Style = style
编译正常,但按钮没有明显变化。我怎样才能应用它?
【问题讨论】:
-
有没有理由不在 xaml 中执行此操作?
-
感谢您的回复。答案是按钮在运行时才存在(它是动态/以编程方式创建的)。
-
@swabygw,我建议在 window.resources 中声明按钮样式,在某个测试按钮上对其进行调试,然后将样式从资源应用到动态按钮(例如
btn_Step.Style = (Style)Resources["MyButtonsStyle"]) -
好的 - 我想过这样做,但后来我也认为这也必须是一种编程方式。但是你的建议意味着可能没有办法对其进行编程,所以我也会尝试这条路线。
-
我尝试了你的想法,它在 XAML 中工作,但无法让它在代码中切换:btn_Step.Style = Style.Resources("MyButton"),尽管我已将模板放在Windows.Resource 正确。你知道正确的命令是什么吗?
标签: wpf vb.net button styles customization