How to set IsReadOnly / IsEnabled on entire container like Panel or GroupBox using XAML?

surfen picture surfen · Apr 7, 2012 · Viewed 11.4k times · Source

I have a MVVM application that contains multiple views with some complex IsReadOnly rules based on user permissions, view/edit mode and object state.

I would like to set IsReadOnly and/or IsEnabled properties for entire groups of controls in the same container (GroupBox / StackPanel / Grid / UserControl / etc.). The value of this property will be defined in ViewModel.

I've got 3-6 different SomeGroupIsReadOnly properties per UserControl (with a large number of input controls like TextBox, RadioButtons, ComboBoxes and some DataGrids) and I'm looking for a generic, MVVM-friendly solution, that will allow me to reuse Bindings on per-container basis, instead of specifying them for each individual control separately.

How can I set IsReadOnly / IsEnabled on all controls inside container like Panel or GroupBox using XAML?

It doesn't seem that WPF supports this out of the box...

EDIT

I forgot to mention that setting IsEnabled for a container disables an important feature of TextBoxes - being able to copy their contents. I need them to be in IsReadOnly=true state. If there was a workarond for that, then my problem would be solved.

Answer

Dan Busha picture Dan Busha · Apr 7, 2012

Disabling the Panel that contains your controls will also disable the controls inside the Panel. Bind the IsEnabled member of the Panel to a bool property on your ViewModel and set it according to your rules to disable the Panel and all of its children.

Xaml:

<GroupBox IsEnabled="{Binding Path=IsGroupEnabled}">
    <StackPanel>
        <Button Content="Sample Button"/>
        <TextBox Text="Sample text box"/>
    </StackPanel>
</GroupBox>