WPF binding to a boolean on a control

Posted by Jose on Stack Overflow See other posts from Stack Overflow or by Jose
Published on 2010-12-22T15:48:12Z Indexed on 2010/12/22 15:54 UTC
Read the original article Hit count: 233

I'm wondering if someone has a simple succinct solution to binding to a dependency property that needs to be the converse of the property. Here's an example

I have a textbox that is disabled based on a property in the datacontext e.g.:

<TextBox IsEnabled={Binding CanEdit} Text={Binding MyText}/>

The requirement changes and I want to make it ReadOnly instead of disabled, so without changing my ViewModel I could do this:

In the UserControl resources:

<UserControl.Resources>
  <m:NotConverter x:Key="NotConverter"/>
</UserControl.Resources>

And then change the TextBox to:

<TextBox IsReadOnly={Binding CanEdit,Converter={StaticResource NotConverter}} Text={Binding MyText}/>

Which I personally think is EXTREMELY verbose

I would love to be able to just do this(notice the !):

<TextBox IsReadOnly={Binding !CanEdit} Text={Binding MyText}/>

But alas, that is not an option that I know of.

I can think of two options.

  • Create an attached property IsNotReadOnly to FrameworkElement(?) and bind to that property
  • If I change my ViewModel then I could add a property CanEdit and another CannotEdit which I would be kind of embarrassed of because I believe it adds an irrelevant property to a class, which I don't think is a good practice.

The main reason for the question is that in my project the above isn't just for one control, so trying to keep my project as DRY as possible and readable I am throwing this out to anyone feeling my pain and has come up with a solution :)

© Stack Overflow or respective owner

Related posts about wpf

Related posts about binding