【问题标题】:How to programmatically access a datagrid row details control如何以编程方式访问数据网格行详细信息控件
【发布时间】:2011-03-28 01:10:01
【问题描述】:

我有一个包含一些已定义列的数据网格,然后是一个行详细信息模板。如何在后面的代码中访问行详细信息模板中的控件?我有一个按钮,我想以编程方式启用/禁用,但我不知道如何在后面的代码中访问它。我在 MSDN 上看到过这个:

http://msdn.microsoft.com/en-us/library/bb613579.aspx

但这只是描述一个常规数据模板,所以当我尝试它时它不起作用。我的案例是行详细信息数据模板。肯定有人编写了代码来访问数据网格行详细信息模板中的控件,该模板可以对此进行评论(将不胜感激)。

【问题讨论】:

    标签: wpf datagrid rowdetails


    【解决方案1】:

    好的,我想出了如何让这个工作我不得不调整在原始问题的 MSDN 文章中发布的代码......

    DataGridRow row = (DataGridRow)(KeywordsGrid.ItemContainerGenerator.ContainerFromItem(KeywordsGrid.SelectedItem));
    
    // Getting the ContentPresenter of the row details
    DataGridDetailsPresenter presenter = FindVisualChild<DataGridDetailsPresenter>(row);
    
    // Finding Remove button from the DataTemplate that is set on that ContentPresenter
    DataTemplate template = presenter.ContentTemplate;
    Button button = (Button)template.FindName("RemoveItemButton", presenter);
    

    KeywordsGrid 是绑定到我的DataGrid 的变量。请注意,在我对FindVisualChild 的调用中,我使用的是DataGridDetailsPresenter 类而不是ContentPresenter(这是关键......它迫使FindVisualChild 方法一直遍历所有内容演示者,直到我找到了行详细信息的那个)。

    【讨论】:

      【解决方案2】:

      使用 DataGrid.LoadingRowDetails 事件!它更直接。

      我在这里找到了这个: How to change Text of TextBlock which is in DataTemplate of Row Details for each DataGrid Row Details?

      例子:

      xaml

      <DataGrid.RowDetailsTemplate>
           <DataTemplate>
               <TextBlock x:Name="Test">Test</TextBlock>
               </DataTemplate>
      </DataGrid.RowDetailsTemplate>
      

      c#

      private void dgVehicles_LoadingRowDetails(object sender, DataGridRowDetailsEventArgs e)
      {
          TextBlock tbTest = e.DetailsElement.FindName("Test") as TextBlock;
          if (tbTest != null)
          {
              tbTest.Text = "Juhuu";
          }
      }
      

      【讨论】:

        【解决方案3】:

        您能否在网格中显示的对象类型上定义(或已经存在)一个属性,该属性表示按钮的启用状态?如果是,那么修改行详细信息模板以将按钮的 IsEnabled 属性绑定到该属性会更简单。

        【讨论】:

        • 是的,在我的视图模型中,我可以在用于数据网格的类中有一个属性。所以这是一种方法。而且我刚刚想出了如何在类后面的代码中做到这一点。我将其作为单独的答案发布。感谢您的回复!
        猜你喜欢
        • 1970-01-01
        • 2011-03-27
        • 2012-01-06
        • 2011-01-06
        • 2018-12-29
        • 2011-07-20
        • 2011-03-06
        • 2019-06-06
        • 2016-11-24
        相关资源
        最近更新 更多