Silverlight 通过点击按钮显示/隐藏DataGrid的RowDetail
Silverlight 中 DataGrid 的 RowDetail 默认显示方式有三种:一、Collapsed 及不显示;二、Visible 及一直显示;三、VisibleWhenSelected 及选中行时显示。有时我们想让用户来选择显示或隐藏某行的详细信息,虽然使用 VisibleWhenSelected 模式会在选中一行时显示相应的详细信息,但是当更改选中行时,之前选中行的详细信息就会隐藏,而且选中一行后也无法隐藏详细信息。(SelectionModel 设置为 Extended ,RowDetailsVisibilityMode 设置为 VisibleWhenSelected ,按住 Ctrl 键选中多行时也会同时显示多行的详细信息,但是当松开 Ctrl 键再选择某一行时,其他行的详细信息就会自动隐藏)
下面我将通过一个非常简单的演示如何在 DataGrid 的每一行添加一个按钮,通过点击按钮来显示或隐藏相应行的详细信息。先看一下本示例的运行结果图。
一、新建一个 Silverlgiht 项目,命名为 SLDataGridExample 。
二、在项目中添加一个 Person 类,代码如下:
public class Person : INotifyPropertyChanged { private string _name; private int _age; public string Name { get { return _name; } set { _name = value; NotifyPropertyChanged("Name"); } } public int Age { get { return _age; } set { _age = value; NotifyPropertyChanged("Age"); } } public event PropertyChangedEventHandler PropertyChanged; public void NotifyPropertyChanged(string name) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name)); } }
三、在 MainPage.xaml 添加一个 DataGrid 控件,将 DataGrid 的 RowDetailsVisiblityModel 设置为 Collapsed,将 SelectionModel 设置为 Single。DataGrid 的完整代码如下:
<sdk:DataGrid x:Name="datagrid1" AutoGenerateColumns="False" ItemsSource="{Binding}" RowDetailsVisibilityMode="Collapsed" SelectionMode="Single"> <sdk:DataGrid.RowDetailsTemplate> <DataTemplate> <StackPanel Orientation="Vertical" Background="LightGray"> <TextBlock Margin="20,10,0,10" Text="{Binding Name}" /> </StackPanel> </DataTemplate> </sdk:DataGrid.RowDetailsTemplate> <sdk:DataGrid.Columns> <sdk:DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="140" /> <sdk:DataGridTextColumn Header="Age" Binding="{Binding Age}" Width="100" /> <sdk:DataGridTemplateColumn Header="Show/Hide Detail" Width="140"> <sdk:DataGridTemplateColumn.CellTemplate> <DataTemplate> <Button Content="Show/Hide Detail" Width="120" Click="Button_Click" /> </DataTemplate> </sdk:DataGridTemplateColumn.CellTemplate> </sdk:DataGridTemplateColumn> </sdk:DataGrid.Columns> </sdk:DataGrid>
在 DataGrid 的最后一列中添加了一个按钮,DataGrid 的 RowDetailsVisiblityModel 设置为 Collapsed ,我们通过点击这个按钮来显示或隐藏 RowDetail。下面是该按钮的 Click 事件的代码:
FrameworkElement el = datagrid1.Columns.Last().GetCellContent(datagrid1.SelectedItem); DataGridRow row = DataGridRow.GetRowContainingElement(el.Parent as FrameworkElement); row.DetailsVisibility = row.DetailsVisibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
在按钮的 Click 事件中,我们通过当前选中的行获取到当前的 DataGridRow ,然后设置 DataGridRow 的 DetailsVisibility 属性来显示或隐藏当前行的详细信息。然后在代码中添加一些演示用的数据,运行示例,至此通过点击按钮显示或隐藏 RowDetail 效果已经实现,是不是非常简单呢。
示例代码下载 SLDataGridExample.7z