.Net v4 DataGridTextColumn.IsReadOnly, похоже, неисправен - PullRequest
24 голосов
/ 11 июля 2010

Если я создаю привязку к свойству IsReadOnly DataGridTextColumn, оно не актуализируется.Если я установлю это через разметку, это работает.

<DataGridTextColumn IsReadOnly="{Binding IsReferenceInactive}"/> <!-- NOP --> 

<DataGridTextColumn IsReadOnly="True"/> <!-- Works as expected, cell is r/o -->

Свойство IsReferenceInactive является DP и работает нормально (В целях тестирования я связал его с флажком, который работал)

Это известное ограничение?

Обновление

Uups, кроме того, что я написал, в окне вывода есть сообщение:

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

Кажется, что это:

http://connect.microsoft.com/VisualStudio/feedback/details/530280/wpf-4-vs2010-datagrid-isreadonly-does-not-work-with-binding-to-boolean-property

Ответы [ 6 ]

30 голосов
/ 06 сентября 2013

То же, что и кодекайзен, но проще:

<DataGridTextColumn>
  <DataGridTextColumn.CellStyle>
    <Style>
      <Setter Property="UIElement.IsEnabled" Value="{Binding IsEditable}" />
    </Style>
  </DataGridTextColumn.CellStyle>
</DataGridTextColumn>
15 голосов
/ 11 июля 2010

DataGridColumn s не являются частью визуального дерева и не участвуют в таком связывании. Чтобы обойти это, я использую 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>

Есть и другие обходные пути, которые я нашел слишком хакерскими, но они работают; для остроумия: http://blogs.msdn.com/b/jaimer/archive/2008/11/22/forwarding-the-datagrid-s-datacontext-to-its-columns.aspx

3 голосов
/ 14 ноября 2015

Я нашел это решение, которое позволяет привязывать данные, когда DataContext не наследуется: http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/

Добавьте класс BindingProxy, который написал Томас, и добавьте этот ресурс к вашему DataGrid:

<DataGrid.Resources>
    <local:BindingProxy x:Key="proxy" Data="{Binding}" />
</DataGrid.Resources>

Теперь вы можете привязать свой DataContex через Data свойство BindingProxy, как и следовало ожидать.

<DataGridTextColumn Header="Price"
                    Binding="{Binding Price}"
                    IsReadOnly="{Binding Data.LockFields, Source={StaticResource proxy}}"/>
0 голосов
/ 09 июля 2018

Я нашел хорошее решение использовать DataGridColumns с привязкой, используя MarkupExtension.Таким образом можно использовать привязки с преобразователями: https://stackoverflow.com/a/27465022/9758687

0 голосов
/ 06 октября 2015

Если вам нравится решение @ codekaizen, но он будет выглядеть как отключенный TextBox, то это поможет:

<DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBox IsEnabled="{Binding Path=myBool}" 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>
0 голосов
/ 20 апреля 2015

Привязка DataGridTextColumn работает только для свойства Text, но не для других свойств DataGridTextColumn.

Решение: DataGridTextColumn указывает DataGrid создать TextBlock для каждой строки иэтот столбец.Вы можете определить стиль для TextBlock и связать Style с Style.Key с TextBlock этого столбца (ElementStyle).

Конечно, теперь TextBlock нужно найти объект из списка данных.Это можно сделать с помощью привязки RelativeSource с помощью AncestorType = DataGridRow.Затем DataGridRow предоставляет доступ к объекту.

Примерно так:

<Window.Resources>
  <Style x:Key="IsReadOnlyStyle" TargetType="TextBlock">
    <Setter Property="IsReadOnly" 
      Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}, 
      Path =Item.NoOutput/>
  </Style>
</Window.Resources>

<DataGrid>
  <DataGrid.Columns>
    <DataGridTextColumn Header="Value" Width="*" Binding="{Binding Value}" ElementStyle="{StaticResource IsReadOnlyStyle}"/>
</DataGrid.Columns>

Сложно, верно?Я рекомендую вам прочитать мою подробную статью о форматировании сетки данных по адресу: http://www.codeproject.com/Articles/683429/Guide-to-WPF-DataGrid-formatting-using-bindings?msg=5037235#xx5037235xx

Удачи, вам это нужно: -)

...