簡體   English   中英

如何在代碼中將Silverlight 3 DataGridCell置於編輯模式?

[英]How can I put a Silverlight 3 DataGridCell into edit mode in code?

我希望能夠在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();
}

我單擊按鈕並選擇了正確的單元格,但它不會在單元格上進行編輯。 需要手動點擊才能實現這一目標。

我不確定為什么你需要使用VisualTreeManager找到DataGridCell,我也不知道你現在如何正確地開始編輯。 您可以簡單地將單元格的視覺狀態設置為編輯。

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

當你做上面這樣的事情時,我不確定網格是如何表現的。 如果您需要DataGrid來幫助您將更改還原到某行,您可能會發現有點梨形狀。

“標准”方法是將DataGrid SelectedItem屬性設置為行所表示的項,將CurrrentColum屬性設置為DataGridColumn對象,該對象表示找到該單元格的列。 然后調用BeginEdit方法。

我無法正確理解您的問題,但我遇到了類似的問題

我想讓只有少數網格單元可編輯而其余部分則不可編輯。 我沒有創建邏輯並將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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM