Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridTextColumn.IsReadOnly seems to be faulty

Tags:

.net

wpf

datagrid

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')

like image 383
HCL Avatar asked Jul 11 '10 11:07

HCL


3 Answers

Same as codekaizen but simpler:

<DataGridTextColumn>
  <DataGridTextColumn.CellStyle>
    <Style>
      <Setter Property="UIElement.IsEnabled" Value="{Binding IsEditable}" />
    </Style>
  </DataGridTextColumn.CellStyle>
</DataGridTextColumn>
like image 195
hansmaad Avatar answered Oct 21 '22 18:10

hansmaad


DataGridColumns 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

like image 27
codekaizen Avatar answered Oct 21 '22 17:10

codekaizen


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}}"/>
like image 8
Ryan Mathewson Avatar answered Oct 21 '22 17:10

Ryan Mathewson