K L
K L

Reputation: 13

WPF: Adding a Trigger to a Button

I am currently coding a program with a WPF UI and I have a button which is either close or cancel, depending on if there were any changes made on the page. To achieve this I want to use a trigger (wrapped in a style) on the button so that when the dependency property HasChanges is true the button will change from "Close" to "Cancel". So far my program displays "Close" as the button's text, but nothing happens when my dependency property HasChanges becomes true. The WPF page is being written in VB.Net and 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.

Upvotes: 1

Views: 4281

Answers (1)

Kent Boogaart
Kent Boogaart

Reputation: 178660

I'm at a loss as to why you'd do this in code and not XAML, but I think it's just that your trigger doesn't know where to look for the custom dependency property. With your code as is, it will look for the HasChanges property on the button itself. Is that intended? Maybe you need to set the Trigger's SourceName property. Or perhaps using a different trigger type altogether (eg. a DataTrigger) would be easier.

Upvotes: 1

Related Questions