Does anyone know how to change the IsReadOnly property of controls (TextBox, ComboBox, etc.) in a WPF HierarchicalDataTemplate dynamically?
I want to be able to make the controls contained in the HierarchicalDataTemplate editable for some users and read-only for others.
I have tried binding the IsReadOnly property on each control in the HierarchicalDataTemplate to a predetermined Boolean value in the page's ViewModel, but am unable to get the binding to work. Any help is greatly appreciated.
VIEWMODEL:
private bool _isReadOnlyBool;
public bool isReadOnlyBool
{
get { return _isReadOnlyBool; }
set
{
_isReadOnlyBool = value;
RaiseChange("isReadOnlyBool");
}
}
Here I show a TreeView control containing a HierarchicalDataTemplate. Notice that I attempt to Bind to the IsReadOnly value of the TextBox in the HierarchicalDataTemplate, to the Boolean "isReadOnlyBool" value from the page's ViewModel.
VIEW:
<TreeView HorizontalAlignment="Center" x:Name="treeView1" VerticalAlignment="Top" ItemsSource="{Binding Path=rsParentChild}" Background="Transparent" BorderThickness="0" BorderBrush="Transparent" >
<TreeView.ItemContainerStyle>
<Style>
<Setter Property="TreeViewItem.IsExpanded" Value="True"/>
</Style>
</TreeView.ItemContainerStyle>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=rsParentChild, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<Grid Focusable="False" Margin="5,10,5,10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Label Content="Action Text" FontSize="8" Grid.Row="0" Grid.Column="0"/>
<TextBox Grid.Row="1" Grid.Column="0"
IsReadOnly="{Binding isReadOnlyBool, RelativeSource={RelativeSource AncestorType={x:Type Page}}}"
Background="#99FFFFFF"
BorderBrush="Black"
Text="{Binding Path=actionText, Mode=TwoWay}"
TextWrapping="Wrap" Margin="0,0,0,0"
LostFocus="TextBox_LostFocus"
/>
</Grid>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
I get the following binding error:
System.Windows.Data Error: 40 : BindingExpression path error: 'isReadOnlyBool' property not found on 'object' ''actions' (Name='')'. BindingExpression:Path=isReadOnlyBool; DataItem='actions' (Name=''); target element is 'TextBox' (Name=''); target property is 'IsReadOnly' (type 'Boolean')
