如何将行为附加到 WPF DataGrid 中的 DataGridCells? [英] How do I attach a behavior to the DataGridCells in a WPF DataGrid?

查看:25
本文介绍了如何将行为附加到 WPF DataGrid 中的 DataGridCells?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can add the behavior to a DataGrid easily (assuming 'i' is the namespace for Microsoft interactivity library):

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

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

Is there a way to attach a behavior to the DataGridCells in the DataGrid?

推荐答案

如果您想知道如何通过 XAML 实现这一点,恐怕这是不可能的,因为 DataGridCells 是动态生成的.但是,如果您能够在创建时捕获每个 DataGridCell,则可以通过编程方式附加行为.

If you are figuring out how this could be made via XAML I'm afraid it's not possible, due to DataGridCells are generated dynamically. But you can attach a behavior programmatically if you are able to catch each DataGridCell whilst it's been created.

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

For instance, you can create your own DataGridTemplateColumn and override its GenerateElement method. First parameter accepted by this method is your desired DataGridCell. When this method is called you can attach your Behavior this way:

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 中使用这种类型的列.

Now you can use this type of column in your DataGrid like other regular columns.

另一种方法:

创建样式并将其应用于 XAML 中的 属性,然后将 Template 属性设置为您想要的任何内容.现在您可以将行为设置为模板的可视化树的根.例如:

Create a style and apply it to <DataGrid.CellStyle> property in your XAML and then set the Template property to whatever you want. Now you can set the Behavior to the root of the Visual Tree of your template. For example:

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

这篇关于如何将行为附加到 WPF DataGrid 中的 DataGridCells?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆