如何在代码中将Silverlight 3 DataGridCell置于编辑模式?

时间:2010-01-25 10:42:29

标签: silverlight silverlight-3.0 datagrid

我希望能够在Silverlight 3.0 DataGrid中选择一个特定的单元格并将其置于编辑模式。我可以使用VisualTreeManager来定位单元格。如何切换到编辑模式?

每个DataGridCell在VisualTreeManager中都是这样的:

          System.Windows.Controls.DataGridCell
            System.Windows.Controls.Grid
              System.Windows.Shapes.Rectangle
              System.Windows.Controls.ContentPresenter
                System.Windows.Controls.TextBlock
              System.Windows.Shapes.Rectangle
              System.Windows.Shapes.Rectangle

使用包含我要编辑的文本的TextBlock。

更新

按照@AnthonyWJones的建议,以下是我尝试使用BeginEdit()的方法。

我想保持简单,所以我想我会在第一行选择一列。即使这证明超出了我的SL知识!最后,我通过创建一个名为firstRow的字段来获取第一行来保存它:

private DataGridRow firstRow;

为DataGrid添加了一个LoadingRow处理程序:

LoadingRow="computersDataGrid_LoadingRow"

private void computersDataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
    if (this.firstRow == null)
        this.firstRow = e.Row;
}

然后在面板上添加一个按钮以触发编辑:

private void Button_Click(object sender, RoutedEventArgs e)
{
    this.dataGrid.SelectedItem = this.firstRow;
    this.dataGrid.CurrentColumn = this.dataGrid.Columns[4];
    this.dataGrid.BeginEdit();
}

我单击按钮并选择了正确的单元格,但它不会在单元格上进行编辑。需要手动点击才能实现这一目标。

2 个答案:

答案 0 :(得分:2)

我不确定为什么你需要使用VisualTreeManager找到DataGridCell,我也不知道你现在如何正确地开始编辑。您可以简单地将单元格的视觉状态设置为编辑。

 VisualStateManager.GoToState(myDataGridCell, "Editing", true);

当您执行上述操作时,我不确定网格的行为方式。如果您需要DataGrid来帮助您将更改还原为一行,您可能会发现有点梨形状。

“标准”方法是将DataGrid SelectedItem属性设置为行所代表的项,将CurrrentColum属性设置为代表的DataGridColumn对象到找到单元格的列。然后调用BeginEdit方法。

答案 1 :(得分:0)

我无法正确理解您的问题,但我遇到了类似的问题

我想让只有少数网格单元可编辑而其余部分不可编辑。我没有创建逻辑并将ReadOnly指定为true / false,而是做了一件简单的事情。

  • 标记整个Grid的单元格是可写的,IsReadOnly为false
  • 设置事件PreparingCellForEdit并发送回调
  • 当您双击单元格时,它将进入编辑模式
  • 检查此单元格是否可以编辑
  • 如果允许编辑,请继续
  • 如果该单元格是ReadOnly,则调用CancelEdit

示例代码就像

namespace foo
{
    public class foobar
    {
        public foobar()
        {
            sampleGrid = new DataGrid();
            sampleGrid.IsReadOnly = false;
            sampleGrid.PreparingCellForEdit += new EventHandler<DataGridPreparingCellForEditEventArgs>(sampleGrid_PreparingCellForEdit);
        }

        void sampleGrid_PreparingCellForEdit(object sender, DataGridsampleGrid_PreparingCellForEditEventArgs e)
        {
            if (sampleGrid.SelectedItem != null)
            {
                bool isWritableField = CheckIfWritable()

                if (isWritableField == false)
                {
                    sampleGrid.CancelEdit();
                }

                // continue with your logic
            }
        }

        private DataGrid sampleGrid;
    }
}