【问题标题】:Getting a control from a DataGridCell从 DataGridCell 获取控件
【发布时间】:2011-05-23 14:19:58
【问题描述】:

假设我在 DataGridTemplateColumn 中有一个任意控件,我想知道如何获取该控件,因为我已检索到包含该控件的 DataGridCell。

我的包含 DataGrid 的 XAML 文件如下:

    <DataGrid Name="dgMovement">
...    
    <DataGridTemplateColumn Header="Target %">
       <DataGridTemplateColumn.CellTemplate>
          <DataTemplate>
            <vi:PercentageEditor Value="{Binding TargetPercentage, Mode=TwoWay,
                      UpdateSourceTrigger=PropertyChanged}" Width="100px"  
                      cal:Message.Attach="[Event PreviewLostKeyboardFocus] = [Action ChangeTargetPercentage];[Event PreviewGotKeyboardFocus] = [Action OnFocus]" 
                      Name="aa" />
          </DataTemplate>
       </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>...

我使用以下扩展方法检索了 DataGridCell:

DataGridCell cell = view.dgMovement2.GetCell(index, 6);

扩展方法,包含在静态类中找到here

问题是,一旦获得 DataGridCell,如何检索“PercentageEditor”?有谁能够帮助我?任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: c# wpf datagrid


    【解决方案1】:

    您可以使用控件的名称在模板中找到它,例如

    <DataGridTemplateColumn>
        <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <uc:Bogus x:Name="root" ItemsSource="{Binding Machines}"/>
            </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
    
    var cell = dataGrid.GetCell(5, 0);
    var cp = (ContentPresenter)cell.Content;
    var bogus = (Bogus)cp.ContentTemplate.FindName("root", cp);
    

    但是请注意,这通常不是必要的,因为修改模板化控件大部分可以单独使用数据绑定、附加属性和事件来完成。一般来说,我会通过代码将模板访问限制为自定义控件(通常有designated parts)。

    【讨论】:

    • 很高兴它有帮助 :) (您可以通过单击它左侧的复选标记大纲来接受这个答案)
    • 几年后,我仍然发现 thia 很有用。谢谢。
    【解决方案2】:

    这对我有用 (C#)

            DataGridRow row = (DataGridRow)dgContacts.ItemContainerGenerator.ContainerFromItem(item);
                var cell = dgContacts.Columns[0];
    
                var cp = (ContentPresenter)cell.GetCellContent(row);
                CheckBox rowSelected = (CheckBox)cp.ContentTemplate.FindName("Edit", cp);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多