WPF: add a trigger to a button
I am currently coding a WPF UI program and I have a button that either closes or cancels, depending on whether any changes have been made to the page. For this, I want to use a trigger (wrapped in style) on the button, so that when the HasChanges dependency property is true, the button will change from Close to Cancel. So far, my program displays "Close" as the button text, but nothing happens when my HasChanges dependency property becomes true. The WPF page is written in VB.Net, not XAML.
So far I have:
Private Sub SetUpMyButton()
Me.MyButton.Style = Me.GetMyButtonStyle()
End Sub
Private Function GetMyButtonStyle() As Style
Dim hasChangesTrigger as New Trigger
hasChangesTrigger.Property = CustomControl.HasChangesProperty
hasChangesTrigger.Value = True
hasChangesTrigger.Setters.Add(New Setter(Button.ContentProperty, "Cancel"))
Dim hasChangesStyle as New Style
hasChangesStyle.TargetType = GetType(Button)
hasChangesStyle.Setters.Add(New Setter(Button.ContentProperty, "Close"))
hasChangesStyle.Triggers.Add(hasChangesTrigger)
hasChangesStyle.Seal()
Return hasChangesStyle
End Function
Any help is greatly appreciated.
source to share
I don't understand why you are doing this in code and not in XAML, but I think your trigger doesn't know where to look for the custom dependency property. With your code as it is, it will look for the HasChanges property on the button itself. Is this intended? Perhaps you need to set a property Trigger
SourceName
. Or perhaps just use a different type of trigger (like a DataTrigger
).
source to share