0

DataGridCell は、コントロールの VisualTree に表示されません。

グリッド内のスタック パネルに Rectangle と Label を含む DataGridTemplateColumn があります。

<t:DataGridTemplateColumn>
    <t:DataGridTemplateColumn.CellTemplate>                                
        <DataTemplate>
            <Grid FocusManager.FocusedElement="{Binding ElementName=swatch}">
                <StackPanel Orientation="Horizontal">
                    <Rectangle Name="swatch" PreviewMouseLeftButtonDown="swatch_PreviewMouseLeftButtonDown" />
                    <Label/>
                </StackPanel>
            </Grid>
        </DataTemplate>
    </t:DataGridTemplateColumn.CellTemplate>
</t:DataGridTemplateColumn>

親要素がnullになるPreviewMouseLeftButtonDownまで、イベントがビジュアルツリーを上向きに反復するようにしたかったのです。DataGridCellGrid

private void swatch_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {          
            DataGridCell cell = null;

            while (cell == null)
            {
                cell = sender as DataGridCell;
                sender = ((FrameworkElement)sender).Parent;
            }

            MethodForCell(sender);
        }

以下のリンクを読むと、DataGrid のビジュアル ツリーで、UIControls が の content プロパティとして設定されているようDataGridCellです。では、Rectangle から DataGridCell を取得するにはどうすればよいでしょうか。

http://blogs.msdn.com/b/vinsibal/archive/2008/08/14/wpf-datagrid-dissecting-the-visual-layout.aspx

4

2 に答える 2

2

これでイベントハンドラーを変更します。

private void swatch_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {         
            DataGridCell cell = null;

            while (cell == null)
            {
                cell = sender as DataGridCell;
                if (((FrameworkElement)sender).Parent != null)
                    sender = ((FrameworkElement)sender).Parent;
                else 
                    sender = ((FrameworkElement)sender).TemplatedParent;
            }
        }
于 2012-07-19T20:34:30.337 に答える
0

私はこれがはるかに優れていることを発見しました

public static T GetVisualParent<T>(Visual child) where T : Visual
    {
        T parent = default(T);
        Visual v = (Visual)VisualTreeHelper.GetParent(child);
        if (v == null)
            return null;
        parent = v as T;
        if (parent == null)
        {
            parent = GetVisualParent<T>(v);
        }
        return parent;
    }

そして、あなたはそれをこのように呼ぶでしょう:

var cell = GetVisualParent<DataGridCell>(e.Source);
于 2013-01-14T17:28:33.930 に答える