Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

c# - 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.

My XAML file containing the DataGrid is as follows:

    <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 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? Can anybody help me? Any help would be greatly appreciated. Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the name of the control to find it in the template, e.g.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...