所以,我正在构建一个基于 MySQL 的程序。我有许多数据列,从整数到双精度数到日期再到字符串,我刚刚决定用模板列创建整个表,以便在 UI 和编程方面保持一致。该系统的关键点是当用户退出单元格时,它需要自动向数据库发送新信息。为了在过去适应这种情况(我遇到其他被动问题),我只需找到已选择的列和行,将坐标传递给底层数据表,并使用它来创建更新字符串并将它们更新到数据库(这有点简化)。
这导致我进入我的新问题。以前我使用的是文本列,现在我使用的是带有文本框(或蒙面文本框)的模板列。当单击单元格时,文本列会固有地处理单元格选择,以便获得选择坐标,而模板列不会很好地处理可视化树,并且不会选择容器单元格,除非单元格被选项卡或以其他方式导航到,但不是在单击时。我试图通过在单击文本框时手动处理可视树来手动选择单元格,但无济于事。奇怪的是,该过程一直有效,直到我单击必须滚动才能到达的列(相同)。有没有人对如何解决这个问题有任何建议?这是我的 XAML 和代码隐藏示例。
XAML:
<DataGrid x:Name="datagrid_1" PreviewMouseLeftButtonDown="UIElement_OnMouseLeftButtonDown1">
<DataGrid.Columns>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<xctk:MaskedTextBox LostFocus="textbox1_LostFocus" BorderBrush="Transparent" AutoSelectBehavior="OnFocus" Text="{Binding Path = penetration, Mode = TwoWay, ValidatesOnExceptions = true, NotifyOnValidationError = false, UpdateSourceTrigger = PropertyChanged}" Mask="000 %" PromptChar=" " HidePromptOnLeave="True"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGrid.Columns>
</DataGrid>
代码隐藏:
private void UIElement_OnLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (sender.GetType().ToString() == "TextBox")
{
var dep = (DependencyObject)e.OriginalSource;
dep = VisualTreeHelper.GetParent(dep);
if (dep == null)
{
return;
}
if (dep is DataGridCell)
{
datagrid_1.SelectedItems[0] = dep;
}
}
}
private void textbox1_LostFocus(object sender, RoutedEventArgs e)
{
try
{
int rowindex = datagrid_1.Items.IndexOf(datagrid_1.SelectedCells[0].Item);
int columnindex = datagrid_1.SelectedCells[0].Column.DisplayIndex;
string groupnumber = datatable1.Rows[rowindex][1].ToString();
string columnname = datatable1.Columns[columnindex].ColumnName.ToString();
string newinfo = datatable1.Rows[rowindex][columnindex].ToString();
instantupdatecall(groupnumber, columnname, newinfo);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
我试图简化一切以使其更容易适应,但我留下了重要的部分。如果有人对如何使这项工作有任何建议,我将不胜感激。