If I create a binding to the IsReadOnly
property of the DataGridTextColumn
, it does not actualize. If I set it through markup, it works.
<DataGridTextColumn IsReadOnly="{Binding IsReferenceInactive}"/> <!-- NOP -->
<DataGridTextColumn IsReadOnly="True"/> <!-- Works as expected, cell is r/o -->
The IsReferenceInactive
property is a DP and works fine (For testing purposes I've bound it to a checkbox, that worked)
Is this a known limitation?
Update
Uups, other than I wrote, there is a message in the output window:
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=IsReferenceInactive; DataItem=null; target element is 'DataGridTextColumn' (HashCode=23836176); target property is 'IsReadOnly' (type 'Boolean')
Same as codekaizen but simpler:
<DataGridTextColumn>
<DataGridTextColumn.CellStyle>
<Style>
<Setter Property="UIElement.IsEnabled" Value="{Binding IsEditable}" />
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
DataGridColumn
s are not part of the visual tree, and don't participate in binding like this. The way I get around it is to use DataGridTemplateColumn
.
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=myProperty}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox IsEnabled="{Binding Path=myBool}" Text="{Binding Path=myProperty, Mode=TwoWay}" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
There are other workarounds, which I've found a bit too hackish, but they do work; to wit: http://blogs.msdn.com/b/jaimer/archive/2008/11/22/forwarding-the-datagrid-s-datacontext-to-its-columns.aspx
I found this solution which allows you to bind to data when the DataContext is not inherited: http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/
Add the BindingProxy
class Thomas wrote and add this resource to your DataGrid
:
<DataGrid.Resources>
<local:BindingProxy x:Key="proxy" Data="{Binding}" />
</DataGrid.Resources>
Now you can bind to your DataContex
via the Data
property of the BindingProxy
just as you would expect.
<DataGridTextColumn Header="Price"
Binding="{Binding Price}"
IsReadOnly="{Binding Data.LockFields, Source={StaticResource proxy}}"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With