简体   繁体   English

从 DataGridCell 获取控件

[英]Getting a control from a DataGridCell

Assuming that I have an arbitrary control inside a DataGridTemplateColumn, I wish to know how to get the control, given that I have retrieved the DataGridCell which contains that control.假设我在 DataGridTemplateColumn 中有一个任意控件,我想知道如何获取控件,因为我已经检索到包含该控件的 DataGridCell。

My XAML file containing the DataGrid is as follows:我的包含 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>...

I retrieved the DataGridCell using extension methods as follows:我使用扩展方法检索了 DataGridCell,如下所示:

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

The extension methods, contained in a static class is found here包含在静态类中的扩展方法可以在这里找到

The question is, how to I retrieve the "PercentageEditor", once I got the DataGridCell?问题是,一旦获得 DataGridCell,如何检索“PercentageEditor”? Can anybody help me?有谁能够帮助我? Any help would be greatly appreciated.任何帮助将不胜感激。 Thanks!谢谢!

You can use the name of the control to find it in the template, eg您可以使用控件的名称在模板中找到它,例如

<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);

Note however that this usually should not be necessary as modifying templated controls for the most part can be done using data binding, attached properties and events alone.但是请注意,这通常不是必需的,因为在大多数情况下修改模板化控件可以单独使用数据绑定、附加属性和事件来完成。 In general i would restrict template access via code to custom controls (which often have designated parts ).一般来说,我会通过代码将模板访问限制为自定义控件(通常具有指定的部分)。

This worked for me (C#)这对我有用(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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM