WPF binding to a boolean on a control
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 i开发者_Python百科s not an option that I know of.
I can think of two options.
- Create an attached property
IsNotReadOnly
toFrameworkElement
(?) and bind to that property - If I change my ViewModel then I could add a property
CanEdit
and anotherCannotEdit
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 :)
精彩评论