简体   繁体   中英

How do I attach a behavior to the DataGridCells in a WPF DataGrid?

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>

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

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.

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);
    }
}

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

Another approach:

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM