[英]How do I attach a behavior to the DataGridCells in a WPF DataGrid?
我可以輕松地將行為添加到DataGrid
(假設“ i”是Microsoft交互庫的名稱空間):
<DataGrid>
<i:Interaction.Behaviors>
<MyDataGridBehavior />
</i:Interaction.Behaviors>
</DataGrid>
有沒有一種方法可以將行為附加到DataGridCells
中的DataGrid
?
如果您想知道如何通過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
屬性設置為所需的任何樣式。 現在,您可以將“行為”設置為模板的可視樹的根。 例如:
<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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.