开发者

How to get cell lreference

If I have a control (combobox, with a SelectionChanged-event in code-behind) in DataGrid. So, from _SelectionChanged-event, can I get reference of it's container-cell of the grid? Plz Help!!

<DataGridTemplateColumn Width="100">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
             <TextBlock Text="{Binding Path=QuotationItemCode}"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>

    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">

                <ComboBox Height="22" Width="100"   Name="cmbQuotationItemCode"
                          ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.vwProducts}"
                          DisplayMemberPath="itM_Code" 
   开发者_如何转开发                       SelectedValuePath ="itM_Id" 
                          Tag="{Binding RelativeSource={RelativeSource Self}, Path=SelectedItem.Row[2]}"
                          SelectedValue="{Binding Path=QuotationItemId}" 
                          Text="{Binding Path=QuotationItemCode}" SelectionChanged="cmbQuotationItemCode_SelectionChanged">
                </ComboBox>
                <TextBlock Name="txtQuotationItemDescription" Text="{Binding Path=DetailDescription, IsAsync=True}" Height="19"></TextBlock>

            </StackPanel>
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>

</DataGridTemplateColumn>


You can walk the visual tree up from the ComboBox until you hit a DataGridCell, using VisualTreeHelper like this:

    private static T FindAncestor<T>(DependencyObject child) where T : DependencyObject
    {
        var parentObject = VisualTreeHelper.GetParent(child);

        if(parentObject == null || parentObject is T) {
            return (T)parentObject;
        }

        return FindAncestor<T>(parentObject);
    }

    private void cmbQuotationItemCode_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var cell = FindAncestor<DataGridCell>((DependencyObject)sender);
        ...
    }

That said, don't forget about DataGridTemplateColumn.CellStyle - perhaps you can solve your problem with a Style!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜