Binding IsEnabled for parent ViewModel instead of UserControl ViewModel

I developed a custom control in SilverLight that contains several child controls. Textboxes, ComboBoxesand so on.

The problem is that when I include this UserControlin the parent view and set the value for the full control IsEnabled=False, the child controls in this particular one UserControlare still included.

I finally found the problem.

Adding something like this means that the binding IsEnabledis in the binding UserControl, and not as I expected in the DataContextparent.

<localControls:TeamEmployeeSelector Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2"
          IsEnabled="{Binding CanModify}" DataContext="{Binding Confidentiality}"/>

QUESTION:
But the question still arises, how can I link IsEnabledto the ViewModel of the Parent? Because it is not very elegant to copy a property CanModifyin the ViewModel CanModifyof a control.

+3
source share
5 answers

Instead of modifying the binding in any way (for example, you can make it dependent on another control name, as suggested in another answer), I would highlight the control that will be disabled and the control where it DataContextwill be changed, For example:

<ContentControl IsEnabled="{Binding CanModify}" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2">
    <localControls:TeamEmployeeSelector DataContext="{Binding Confidentiality}"/>
</ContentControl>
+6
source

Here is how I would do it.

Your TeamEmployeeSelector UserControlwill contain one root level element, which by default is Gridand is given the name "LayoutRoot".

IsEnabled UserControl :

 <TextBox IsEnabled="{Binding Parent.IsEnabled, ElementName=LayoutRoot}" ... />

-, CanModify .

, x:Name UserControl, , Parent , . Silverlight 4, 3 WP7. .

+1

, Silverlight, WPF RelativeSource.

.

!

0
<localControls:TeamEmployeeSelector Grid.Row="1" Grid.Column="0"
Grid.ColumnSpan="2" IsEnabled="{Binding ElementName=SomeElementName_With_Parent_ViewModel, Path=DataContext.CanModify}" DataContext="{Binding Confidentiality}"/>
0

. , UserControl DataContext . :

UserControlExample() {
   InitializeComponent();
   RootElement.DataContext = this;
}

RootElement - , RootElement ( Grid ) UserControl.

:

<TextBox x:Name="MainTextBox" IsEnabled={Binding IsEnabled} />

, TextBox DataContext .

, , UserControl IsEnabled , :

<Grid>
   <UserControlExample IsEnabled={Binding CanModify} />
</Grid>

This way you keep your concerns separate. Subelements are not important, which reflects UserControl. They just need to know how to enable / disable when the IsEnabledcontrol property is flipped.

sub-controls IsEnabled bound to --> (UserControlExample is DataContext)
   UserControlExample.IsEnabled bound to -->  (VM is DataContext)
      VM.CanModify  
0
source

All Articles