【问题标题】:WPF DataGrid switch template between view mode and edit modeWPF DataGrid 在查看模式和编辑模式之间切换模板
【发布时间】:2009-06-03 14:01:21
【问题描述】:

如果窗口左侧有一个 WPF DataGrid,右侧有一个区域用于显示所选记录。所选记录由Textboxes 和ComboBoxes 组成,在单击编辑按钮之前它们都处于禁用状态。一切正常。

但是,当 DataGridSelectedItem 被更改时,填充 ComboBoxes 似乎有点笨拙。在单击“编辑”按钮之前,可以使用更轻松的控件(例如 TextBlock),然后可以将 TextBlocks 切换为 ComboBoxes。

我确信这可以通过某种模板来完成,但是当我尝试对此进行试验时,与 ComboBoxes 关联的所有事件都会报告错误,因为它们不再存在,因为它们已在“查看模式”中替换为 TextBlocks。

我可能会解决这个问题,因此不胜感激。

【问题讨论】:

    标签: wpf datagrid templating


    【解决方案1】:

    这里很好article

    将单击编辑应用到 DataGrid 中的所有单元格

    1. 将以下样式粘贴到 DataGrid 的资源中
    2. 将方法粘贴到后面的代码中

    仅对 DataGrid 中的某些单元格应用单击编辑

    1. 在样式上设置 x:Key(例如)
    2. 将样式粘贴到 DataGrid 的资源中
    3. 将样式应用于您希望单击编辑的列的 CellStyle 属性(例如)
    4. 将方法粘贴到后面的代码中

      //
      // SINGLE CLICK EDITING
      //
      private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
      {
          DataGridCell cell = sender as DataGridCell;
          if (cell != null && !cell.IsEditing && !cell.IsReadOnly)
          {
              if (!cell.IsFocused)
              {
                  cell.Focus();
              }
              DataGrid dataGrid = FindVisualParent<DataGrid>(cell);
              if (dataGrid != null)
              {
                  if (dataGrid.SelectionUnit != DataGridSelectionUnit.FullRow)
                  {
                      if (!cell.IsSelected)
                          cell.IsSelected = true;
                  }
                  else
                  {
                      DataGridRow row = FindVisualParent<DataGridRow>(cell);
                      if (row != null && !row.IsSelected)
                      {
                          row.IsSelected = true;
                      }
                  }
              }
          }
      }    
      
      static T FindVisualParent<T>(UIElement element) where T : UIElement
      {
          UIElement parent = element;
          while (parent != null)
          {
              T correctlyTyped = parent as T;
              if (correctlyTyped != null)
              {
                  return correctlyTyped;
              }
      
              parent = VisualTreeHelper.GetParent(parent) as UIElement;
          }
          return null;
      } 
      

    【讨论】:

    【解决方案2】:

    ContentTemplateSelector 属性应该允许您根据当前模式(查看/编辑)选择一个或另一个模板

    【讨论】:

      【解决方案3】:

      标记的答案链接已失效。

      这可能会有所帮助: http://wpf.codeplex.com/wikipage?title=Single-Click%20Editing

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-24
        • 1970-01-01
        • 1970-01-01
        • 2013-02-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-24
        相关资源
        最近更新 更多