我有一个 DataGrid ,只有一列(X)。根据窗口中的其他 CheckBoxes ,某些行可能是只读的。现在,我发现这样做的最简单方法是获取相关的 DataGridRows 并设置其.IsEnabled = false
并将其背景更改为灰色。
这会阻碍鼠标选择细胞,鼠标也会双击它们。同样,使用键盘方向键也不允许进入只读行。但是,如果我在最后一个可编辑行中编辑单元格,则以 Enter 结束(此时编辑的单元格显然仍处于选中状态,但不再处于编辑模式),键入更多值并按< kbd>再次输入,改变了所谓的只读行的值。
以下是一本&#34;故事书&#34;我的意思是:
我们有:
我上面使用了术语&#34; readonly&#34;,但实际上我必须定义DataGridRow.IsEnabled = false
,这可能是导致此错误的原因。但是,由于 DataGridRow 不包含.IsReadOnly
属性,因此这是我可以定义的唯一课程。
它的价值在哪里,这是相关的代码。您会注意到 DataGrid 的绑定完全出现在代码隐藏中,但这是因为绑定源根据窗口的其他部分发生了变化。
XAML
<DataGrid Grid.Column="0"
x:Name="CoordinatesX"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn x:Name="XColumn" Header="X" Width="50"/>
</DataGrid.Columns>
</DataGrid>
CS
这是定义应显示哪个集合的函数。可以注意到,当选中EqualToResults( CheckBox )时,整个列都设置为 ReadOnly 。在这种情况下,不会出现这里出现的问题。然而,这可能仅仅是因为用户无法开始进入可编辑的行。
void ControlBindings()
{
var resultSections = NProjectProperties.Instance.ResultSections;
var cable = DataContext as NCable;
Binding binding;
if (EqualToResults.IsChecked == true)
{
CoordinatesX.ItemsSource = resultSections;
XColumn.IsReadOnly = true;
var cStyle = new System.Windows.Style(typeof(DataGridCell));
cStyle.Setters.Add(new Setter(DataGridCell.BackgroundProperty, Brushes.LightGray));
XColumn.CellStyle = cStyle;
binding = new Binding();
nSections.Value = resultSections.Count;
}
else
{
CoordinatesX.ItemsSource = cable.Points;
XColumn.IsReadOnly = false;
XColumn.CellStyle = null;
binding = new Binding("X");
}
XColumn.Binding = binding;
}
如果选中另一个 CheckBox ,EqualSpacing,则此功能会将必要的行设置为.IsEnabled = false
。
void CheckConstraints()
{
var cable = DataContext as NCable;
int nPoints = cable.Points.Count;
if (EqualSpacing.IsChecked == true)
{
DataGridRow r;
for (int i = 1; i < nPoints - 1; i++)
{
r = CoordinatesX.ItemContainerGenerator.ContainerFromIndex(i) as DataGridRow;
if (r == null)
break;
r.Background = Brushes.LightGray;
r.IsEnabled = false;
}
r = CoordinatesX.ItemContainerGenerator.ContainerFromIndex(nPoints - 1) as DataGridRow;
if (r == null)
return;
r.Background = ((nPoints - 1) % 2 == 0 ? Brushes.White : Brushes.AliceBlue);
r.IsEnabled = true;
}
}
这有什么解决方案吗?我做错了吗?