在 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
它可以编译,但按钮没有明显的变化。 我怎样才能应用它?
我想出了如何使用代码来做到这一点 - 这是我的最终解决方案:
Public Function CreateStyle(ByVal clr1 As SolidColorBrush, ByVal clr2 As SolidColorBrush)
Dim st As New Style
st.TargetType = GetType(Button)
Dim se0 As New Setter
se0.Property = Button.OverridesDefaultStyleProperty
se0.Value = True
st.Setters.Add(se0)
Dim se1 As New Setter
se1.Property = TemplateProperty
Dim ct As New ControlTemplate
'Reference: https://social.msdn.microsoft.com/Forums/vstudio/en-US/ddb7fd77-dea1-40f5-a5b7-30d35ecda70e/creating-a-control-template-with-code-behind?forum=wpf
ct.TargetType = GetType(Button)
Dim fef0 As New FrameworkElementFactory(GetType(Border))
fef0.Name = "Border"
fef0.SetValue(Border.BorderThicknessProperty, New Thickness(1))
fef0.SetValue(Border.BorderBrushProperty, Brushes.Black)
ct.VisualTree = fef0
Dim fef1 As New FrameworkElementFactory(GetType(ContentPresenter))
fef1.SetValue(HorizontalAlignmentProperty, HorizontalAlignment.Center)
fef1.SetValue(VerticalAlignmentProperty, VerticalAlignment.Center)
fef0.AppendChild(fef1)
Dim tr0 As New Trigger
tr0.Property = Button.IsMouseOverProperty
tr0.Value = True
Dim se2 As New Setter
se2.TargetName = "Border"
se2.Property = Button.BackgroundProperty
se2.Value = clr1
tr0.Setters.Add(se2)
ct.Triggers.Add(tr0)
Dim tr1 As New Trigger
tr1.Property = Button.IsMouseOverProperty
tr1.Value = False
Dim se3 As New Setter
se3.TargetName = "Border"
se3.Property = Button.BackgroundProperty
se3.Value = clr2
tr1.Setters.Add(se3)
ct.Triggers.Add(tr1)
se1.Value = ct
st.Setters.Add(se1)
Return st
End Function