如何将行为附加到WPF DataGrid中的DataGridCells?

时间:2015-09-23 13:58:42

标签: c# wpf datagrid

我可以轻松地将行为添加到DataGrid(假设' i'是Microsoft交互库的命名空间):

<DataGrid>
  <i:Interaction.Behaviors>
    <MyDataGridBehavior />
  </i:Interaction.Behaviors>
</DataGrid>

有没有办法将行为附加到DataGridCells中的DataGrid

1 个答案:

答案 0 :(得分:1)

如果您正在弄清楚如何通过XAML进行此操作,我担心这是不可能的,因为DataGridCells是动态生成的。但是,如果您能够在创建每个DataGridCell时捕获它们,则可以以编程方式附加行为。

例如,您可以创建自己的DataGridTemplateColumn并覆盖其GenerateElement方法。此方法接受的第一个参数是您想要的DataGridCell。调用此方法后,您可以通过以下方式附加Behavior

public class MyTemplateColumn : DataGridTemplateColumn
{
    protected override System.Windows.FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
    {
        //Create instance of your behavior
        MyDataGridBehavior b = new MyDataGridBehavior();

        //Attach behavior to the DataGridCell
        System.Windows.Interactivity.Interaction.GetBehaviors(cell).Add(b);

        return base.GenerateElement(cell, dataItem);
    }
}

现在,您可以像使用其他常规列一样在DataGrid中使用此类型的列。

另一种方法:

创建样式并将其应用于XAML中的<DataGrid.CellStyle>属性,然后将Template属性设置为您想要的任何属性。现在,您可以将Behavior设置为模板的Visual Tree的根目录。例如:

<DataGrid.CellStyle>
    <Style TargetType="{x:Type DataGridCell}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type DataGridCell}">
                    <Grid> <!-- root element -->
                        <i:Interaction.Behaviors>
                            <My:MyDataGridBehavior/>
                        </i:Interaction.Behaviors>

                        ... <!-- elements to show content -->

                    </Grid>
                </ControlTemplate>
        </Setter>
    </Style>
<DataGrid.CellStyle>