在WPF中,可以使用DataGrid
控件来显示表格数据,并在单元格上添加MouseOver
事件来显示弹出窗口。以下是一个完整的示例代码:
<DataGrid x:Name="dataGrid" AutoGenerateColumns="False" ItemsSource="{Binding Items}">
<DataGrid.Columns>
<DataGridTextColumn Header="Column1" Binding="{Binding Column1}" />
<DataGridTextColumn Header="Column2" Binding="{Binding Column2}" />
</DataGrid.Columns>
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<EventSetter Event="MouseEnter" Handler="DataGridCell_MouseEnter" />
<EventSetter Event="MouseLeave" Handler="DataGridCell_MouseLeave" />
</Style>
</DataGrid.CellStyle>
</DataGrid>
在这个示例中,我们使用DataGrid
控件来显示数据,并在CellStyle
中添加MouseEnter
和MouseLeave
事件。当鼠标移动到单元格上时,会触发DataGridCell_MouseEnter
事件,当鼠标离开单元格时,会触发DataGridCell_MouseLeave
事件。
接下来,我们需要在代码隐藏中实现这两个事件处理程序:
private void DataGridCell_MouseEnter(object sender, MouseEventArgs e)
{
DataGridCell cell = sender as DataGridCell;
if (cell != null)
{
// 显示弹出窗口
Popup popup = new Popup();
popup.PlacementTarget = cell;
popup.Placement = PlacementMode.MousePoint;
popup.IsOpen = true;
popup.Child = new TextBlock { Text = "Hello, world!" };
}
}
private void DataGridCell_MouseLeave(object sender, MouseEventArgs e)
{
DataGridCell cell = sender as DataGridCell;
if (cell != null)
{
// 隐藏弹出窗口
Popup popup = cell.FindResource("popup") as Popup;
if (popup != null)
{
popup.IsOpen = false;
}
}
}
在这个示例中,我们在DataGridCell_MouseEnter
事件处理程序中创建一个Popup
控件,并将其显示在鼠标指针的位置。在DataGridCell_MouseLeave
事件处理程序中,我们隐藏弹出窗口。
需要注意的是,这个示例中的代码只是一个简单的示例,实际应用中可能需要根据具体需求进行修改和优化。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云