WPF: Element State Binding
I’ve been working with WPF lately. Partly for work, but mostly to teach myself while at the same time being productive. I am definitely one of those people that learns best by doing.
I have been working on adding some encryption to a application recently and I am making a form that will allow the user to enter a password that will be used for the encryption/decryption process.
On the form that I made, I had a checkbox to determine whether they even want to use encryption at all, as well as two password boxes for the password and the confirmation. I wanted to make it such that when they clicked the checkbox that it would enable the password fields and disable them when the checkbox was unchecked. Essentially tie the IsEnabled
property of the PasswordBox’s to the IsChecked
property of the CheckBox.
Well, I could tie a method to the Checked
event of the CheckBox, and then adjust the PasswordBoxes accordingly, or I could do it the WPF way and use Binding to tie the elements together to one another.
Opting for the latter (since I am trying to learn after all), I dug around in my WPF book and in short order, had the answer.
Assuming that the CheckBox is named checkbox1
:
<PasswordBox Name="Password1" Margin="0,5" Width="200" IsEnabled="{Binding ElementName=checkbox1, Path=IsChecked}"/>
What is happening here is that WPF is telling the IsEnabled
property to watch checkbox1
and specifically the IsChecked
property of that control and grab the value from there.
Pretty cool stuff.