Rob Sobers
Rob Sobers

Reputation: 21135

How do I make the IsEnabled property of a button dependent on the presence of data in other controls? (WPF)

I have a "Login" button that I want to be disabled until 3 text boxes on the same WPF form are populated with text (user, password, server).

I have a backing object with a boolean property called IsLoginEnabled which returns True if and only if all 3 controls have data. However, when should I be checking this property? Should it be on the LostFocus event of each of the 3 dependent controls?

Thanks!

vg1890

Upvotes: 1

Views: 844

Answers (4)

Vin
Vin

Reputation: 6145

I think you could use RoutedCommands one of the most useful features of WPF. Basically add a CommandBinding, to use OnExecute and OnQueryCommandEnabled to manage button's enabled state.

Check out this wonderful explanation on using RoutedCommands in WPF

Upvotes: 0

Andrew
Andrew

Reputation: 13221

I'd get the "backing object" to raise the IsLoginEnabled changed event when any of the 3 fields are updated. You can then bind the button to the IsLoginEnabled property and not have to keep checking it.

The pseudocode would look something like this:

Public Event IsLoginEnabledChanged As EventHandler

Public Property User() As String
Get..   ' snipped for brevity
Set(ByVal value As String)
   mUser = value
   RaiseEvent IsLoginEnabledChanged(Me, New EventArgs())
End Set

' do the same in the Set for Password() and Server() properties

The trick to this is naming the Event [PropertyName]Changed (i.e. IsLogonEnabledChanged) - because raising this event will automagically notify any bound controls :o)

Upvotes: 1

Nick
Nick

Reputation: 9183

Can you just databind your IsLoginEnabled right to the Enabled property of the login button?

Upvotes: 0

Totty
Totty

Reputation: 916

Yes, I would say the easiest option would be to check it on the LostFocus or TextChanged event of each of those controls. However, if you want to do a little heavier lifting, you could implement the boolean as a dependency property that you could have bound to the button's Enable. http://msdn.microsoft.com/en-us/library/ms750428.aspx

Upvotes: 0

Related Questions