今天在论坛上看到一个人想实现这样的一个功能:
1. 在datagrid空间里有很多行很多列。
2. 其中的一列有两个空间: button和image
3. 默认情况下,显示Button,如果当鼠标Hover该行的时候,则显示图片,隐藏button;当鼠标离开的时候,就隐藏图片,显示button.
下面是datagrid的 xaml代码:
datagrid
1<data:DataGrid x:Name="peopleDataGrid" Grid.Row="1" Width="auto" Height="auto" MouseEnter="peopleDataGrid_MouseEnter" MouseMove="peopleDataGrid_MouseMove" KeyDown="peopleDataGrid_KeyDown" LoadingRow="peopleDataGrid_LoadingRow" >
2 <data:DataGrid.Columns>
3 <data:DataGridTemplateColumn Header="Primary Key">
4 <data:DataGridTemplateColumn.CellTemplate>
5 <DataTemplate>
6 <StackPanel x:Name="panel" MouseEnter="StackPanel_MouseEnter" MouseLeave="StackPanel_MouseLeave" >
7 <Image x:Name="image" Source="niwazeki01a.jpg" Visibility="Collapsed"></Image>
8 <Button x:Name="btn" Content="Button"></Button>
9 </StackPanel>
10 </DataTemplate>
11 </data:DataGridTemplateColumn.CellTemplate>
12 </data:DataGridTemplateColumn>
13 </data:DataGrid.Columns>
14
15 </data:DataGrid>
如果有实现鼠标的操作,需要用到datagrid两个事件 :MouseEnter 、MouseLeave 。
这两个事件需要在datagrid的rowloading事件里面注册:
注册鼠标的事件
1 private void peopleDataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
2{
3 e.Row.MouseEnter += new MouseEventHandler(Row_MouseEnter);
4 e.Row.MouseLeave += new MouseEventHandler(Row_MouseLeave);
5
6}
事件
1 void Row_MouseLeave(object sender, MouseEventArgs e)
2 {
3 GetChildrenWithParent((DataGridRow)sender, typeof(Button), typeof(Image));
4 ((DataGridRow)sender).Height = 25;
5 }
6
7 void Row_MouseEnter(object sender, MouseEventArgs e)
8 {
9 GetChildrenWithParent((DataGridRow)sender, typeof(Image),typeof(Button));
10 ((DataGridRow)sender).Height = 100;
11 }
12
然后根据鼠标的操作,使用VisualTreeHelper 找到datagrid的controlTemplate中的控件,然后显示或隐藏他们:
控件的显示/隐藏
1private void GetChildrenWithParent(UIElement parent, Type targetType, Type hideType)
2 {
3 int count = VisualTreeHelper.GetChildrenCount(parent);
4
5 for (int i = 0; i < count; i++)
6 {
7 UIElement child = (UIElement)VisualTreeHelper.GetChild(parent, i);
8 if (targetType.ToString() == "System.Windows.Controls.Image")
9 {
10 if (child.GetType() == targetType && ((Image)child).Name == "image")
11 {
12 child.Visibility = Visibility.Visible;
13 }
14
15 if (child.GetType() == hideType && ((Button)child).Name == "btn")
16 {
17 child.Visibility = Visibility.Collapsed;
18 }
19 }
20 else if (targetType.ToString() == "System.Windows.Controls.Button")
21 {
22 if (child.GetType() == targetType && ((Button)child).Name == "btn")
23 {
24 child.Visibility = Visibility.Visible;
25 }
26
27 if (child.GetType() == hideType && ((Image)child).Name == "image")
28 {
29 child.Visibility = Visibility.Collapsed;
30 ((StackPanel)parent).MinHeight = 10;
31 }
32 }
33
34 GetChildrenWithParent(child, targetType,hideType);
35 }
36 }
由于图片 和button控件的高度的差别,在从图片切换到Button的时候,发现datagrid的行变得比较高,没有自适应高度。所以需要在MouseEnter 、MouseLeave 事件中,手动的设置行高。