基本上,我有一个包含多个列的 DataGrid,我想启用(更改 IsReadOnly 属性)一个基于CheckBox IsChecked,位于同一个DataGrid的另一个DataGridTemplateColumn中。
这是代码(的重要部分):
<DataGrid Name="lstTags" Grid.Row="0" ItemsSource="{Binding Path = LinesCollection}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" SelectionMode="Single" LostFocus="lstTags_LostFocus" SelectionChanged="lstTags_SelectionChanged">
<DataGrid.Columns>
<DataGridTemplateColumn x:Name="colAutoScale" Header="Auto Scale">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox x:Name="ckbAutoScale" HorizontalAlignment="Center" IsChecked="{Binding AutoScale, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="Scale" Binding="{Binding Path=Scale}" IsReadOnly="{Binding ElementName ckbAutoScale, Path=IsChecked}" Width="60" />
</DataGrid.Columns>
</DataGrid>
值得一提的是,我还想反转IsChecked属性的值,即
IsChecked = true=>IsReadOnly = false;IsChecked = false=>IsReadOnly = true。
我可能会用一个简单的 Converter 来实现这一点,但我需要第一部分才能正常工作。
编辑:
回答一个好问题,我的目标是禁用相邻的单元格(同一行),而不是整列。
请您参考如下方法:
为您的Scale Column 使用以下绑定(bind):
<DataGridTextColumn Header="Scale" Binding="{Binding Path=Scale}" Width="60" >
<DataGridTextColumn.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridCellsPanel}},Path=Children[0].Content.Content.AutoScale}" />
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
或简单地
<DataGridTextColumn Header="Scale" Binding="{Binding Path=Scale}" Width="60" >
<DataGridTextColumn.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="IsEnabled" Value="{Binding Path=AutoScale}" />
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
输出:
PS: Above Solution 1 is specific to your code, cause
Auto Scalecolumnis at 0Indexthat's why I usedChildren[0]inBinding. Please change if there is any contextual need.
