演练:使用属性自定义 DataGrid 控件

演练:使用属性自定义 DataGrid 控件

Silverlight
 
此主题尚未评级 评价此主题
 

Silverlight DataGrid 控件支持常用表格式设置选项,例如交替显示不同的行背景以及能够显示或隐藏表头、网格线和滚动条。 可以通过设置 DataGrid 属性来进行这些自定义。 属性可以在设计时在 XAML 中设置,也可以在运行时在过程代码中设置。

本演练演示以下任务:

  • 创建数据对象的集合。

  • 创建用户界面以显示数据。

  • 设置列表的数据源。

  • 创建用于设置 DataGrid 选项的用户界面。

  • 添加过程代码以修改 DataGrid 属性。

若要查看 DataGrid 控件的运行示例,请单击下面的链接。

运行此示例

您需要以下组件来完成本演练:

  • Silverlight 5 Beta.

  • 用于 Visual Studio 2010 的 Silverlight Tools.

  • Visual Studio 2010.

可以从 Silverlight 下载站点 下载所有 Silverlight 软件。

第一步是创建一个 Silverlight 项目。

创建 Silverlight 项目

  • 使用 Visual Basic 或 Visual C# 新建一个名为 DGBasicCustomization 的 Silverlight 应用程序项目。 保持选中默认选项“在新网站中承载 Silverlight 应用程序” 有关更多信息,请参见 如何创建新 Silverlight 项目

接下来创建要在 DataGrid 中显示的 Task 对象的集合。

创建 Task 对象的集合

  1. 向 DGBasicCustomization 项目中添加一个名为 Task 的类。

  2. 向 Task 类中添加下面的代码。

    此代码包含 Task 类,该类表示要在 DataGrid 控件中显示的数据对象。

     
    public string Name { get; set; }
    public DateTime DueDate { get; set; }
    public bool Complete { get; set; }
    public string Notes { get; set; }
    
    
    
  3. 打开 MainPage.xaml.vb 或 MainPage.xaml.cs。

  4. 在 MainPage 类构造函数的 InitializeComponent 方法的后面添加以下代码。

    此代码创建一个名为 taskList 的泛型 List<T>,并使用循环以 Task 对象填充集合。 然后将 taskList 设置为 DataGrid的 ItemsSource

     
    // Create a list to store task data.
    List<Task> taskList = new List<Task>();
    int itemsCount = 10;
    // Generate some task data and add it to the task list.
    for (int i = 1; i <= itemsCount; i++)
    {
        taskList.Add(new Task()
        {
            Name = "Task " + i.ToString(),
            DueDate = DateTime.Now.AddDays(i),
            Complete = (i % 3 == 0),
            Notes = "Task " + i.ToString() + " is due on " 
                  + DateTime.Now.AddDays(i) + ". Lorum ipsum..."
        });
    }
    this.dataGrid1.ItemsSource = taskList;
    
    
    

接下来,通过向页面中添加 DataGrid 控件来创建任务列表的用户界面。

创建任务列表的用户界面

  1. 在 DGBasicCustomization 项目中,添加一个对 System.Windows.Controls.Data 程序集的引用。 有关更多信息,请参见 如何:向页中添加 DataGrid 控件

  2. 打开 MainPage.xaml。

  3. 在 <UserControl> 开始标记中添加下面的 XAML。

    此 XAML 将 sdk 前缀映射到 Silverlight SDK 命名空间,如 Silverlight 库的前缀和映射中所述。

    xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"

  4. 在 <UserControl> 开始标记中,将 Width 属性的值更改为 600,将 Height 属性的值更改为 700

  5. 在 <UserControl> 开始标记之后添加下面的 XAML,从而替换现有的 <Grid> 标记。

    此 XAML 添加一个 StackPanel 以及一个名为 dataGrid1 的 DataGrid,前者用于布局目的,后者用于显示任务列表。

     
    <StackPanel x:Name="LayoutRoot" Background="White" Margin="5">
    
    
    ...
    
    
        <sdk:DataGrid x:Name="dataGrid1" Height="350" Width="540" 
                       HorizontalAlignment="Left" >
        </sdk:DataGrid>
    </StackPanel>
    
    
    
  6. 生成并运行此应用程序。

    当应用程序运行时,您将看到一个 DataGrid,它以其默认外观和行为显示 taskList 集合中的任务。

接下来创建 DataGrid 选项的用户界面。

创建 DataGrid 选项的用户界面

  1. 打开 MainPage.xaml。

  2. 在 <StackPanel> 开始标记之后添加下面的 XAML。

    此 XAML 用于添加选择控件,您将使用这些控件在运行时修改 DataGrid 的属性。

     
    <StackPanel Margin="0,0,0,5">
        <StackPanel Orientation="Horizontal">
            <Border BorderBrush="Black" BorderThickness="1" Padding="3" Width="180">
                <StackPanel>
                    <TextBlock Text="DataGrid Options" FontSize="12" />
                    <CheckBox Content="Grid is read-only" 
                              Checked="cbReadOnly_Changed" Unchecked="cbReadOnly_Changed" />
                    <CheckBox Content="Freeze first column" 
                              Checked="cbFreezeColumn_Changed" Unchecked="cbFreezeColumn_Changed"/>
                    <CheckBox Content="Hide first column" 
                              Checked="cbHideColumn_Changed" Unchecked="cbHideColumn_Changed"/>
                    <CheckBox Content="Single Row Selection"
                              Checked="cbSelectionMode_Changed" Unchecked="cbSelectionMode_Changed" />
                    <TextBlock Text="Column Options" FontSize="12" />
                    <CheckBox Content="Allow Column Reordering" IsChecked="true" 
                              Checked="cbColReorder_Changed" Unchecked="cbColReorder_Changed"/>
                    <CheckBox Content="Allow Column Resizing" IsChecked="true"
                              Checked="cbColResize_Changed" Unchecked="cbColResize_Changed"/>
                    <CheckBox Content="Allow Column Sorting" IsChecked="true"
                              Checked="cbColSort_Changed" Unchecked="cbColSort_Changed"/>
                    <TextBlock Text="Scroll Bar Options" FontSize="12" />
                    <CheckBox Content="Vertical Scroll Bars" IsThreeState="True" IsChecked="" 
                              Checked="cbVerticalScroll_Changed" Unchecked="cbVerticalScroll_Changed" 
                              Indeterminate="cbVerticalScroll_Changed" />
                    <CheckBox Content="Horizontal Scroll Bars" IsThreeState="True" IsChecked=""
                              Checked="cbHorizontalScroll_Changed" Unchecked="cbHorizontalScroll_Changed" 
                              Indeterminate="cbHorizontalScroll_Changed"/>
                </StackPanel>
            </Border>
            <Border BorderBrush="Black" BorderThickness="1" Padding="3" Width="180">
                <StackPanel>
                    <TextBlock Text="Alternating Row Background" FontSize="12" />
                    <ComboBox SelectionChanged="cbAltRowBrush_SelectionChanged">
                        <ComboBoxItem Content="Default" IsSelected="True" />
                        <ComboBoxItem Content="Custom" />
                        <ComboBoxItem Content="Null" />
                    </ComboBox>
                    <TextBlock Text="Row Background" FontSize="12" />
                    <ComboBox SelectionChanged="cbRowBrush_SelectionChanged">
                        <ComboBoxItem Content="Default" IsSelected="True" />
                        <ComboBoxItem Content="Custom" />
                        <ComboBoxItem Content="Null" />
                    </ComboBox>
                    <TextBlock Text="Header Visibility" FontSize="12" />
                    <ComboBox SelectionChanged="cbHeaders_SelectionChanged">
                        <ComboBoxItem Content="All"/>
                        <ComboBoxItem Content="Column (Default)" IsSelected="True"/>
                        <ComboBoxItem Content="Row"/>
                        <ComboBoxItem Content="None"/>
                    </ComboBox>
                    <TextBlock Text="Grid Lines Visibility" FontSize="12" />
                    <ComboBox SelectionChanged="cbGridLines_SelectionChanged">
                        <ComboBoxItem Content="All"/>
                        <ComboBoxItem Content="Vertical (Default)" IsSelected="True"/>
                        <ComboBoxItem Content="Horizontal"/>
                        <ComboBoxItem Content="None"/>
                    </ComboBox>
                    <TextBlock Text="Custom Grid Lines" FontSize="12" />
                    <CheckBox Content="Vertical" 
                              Checked="cbCustomGridLineVert_Changed" 
                              Unchecked="cbCustomGridLineVert_Changed"/>
                    <CheckBox Content="Horizontal" 
                              Checked="cbCustomGridLineHorz_Changed" 
                              Unchecked="cbCustomGridLineHorz_Changed"/>
                </StackPanel>
            </Border>
        </StackPanel>
    </StackPanel>
    
    
    

接下来,您将添加代码以处理对用户界面控件所做的更改以及设置 DataGrid 属性。

在代码中设置 DataGrid 属性

  1. 打开 MainPage.xaml.vb 或 MainPage.xaml.cs。

  2. 在 MainPage 类构造函数之后,添加下面的代码。

    此代码将处理您在上一节中添加的 DataGrid 选项用户界面控件的更改事件。 当某个选项更改时,将设置相应的DataGrid 属性

     
    // READ ONLY
    private void cbReadOnly_Changed(object sender, RoutedEventArgs e)
    {
        CheckBox cb = sender as CheckBox;
        if (this.dataGrid1 != null)
            this.dataGrid1.IsReadOnly = (bool)cb.IsChecked;
    }
    // FREEZE COLUMN
    private void cbFreezeColumn_Changed(object sender, RoutedEventArgs e)
    {
        CheckBox cb = sender as CheckBox;
        if (this.dataGrid1 != null)
        {
            if (cb.IsChecked == true)
                this.dataGrid1.FrozenColumnCount = 1;
            else if (cb.IsChecked == false)
                this.dataGrid1.FrozenColumnCount = 0;
        }
    }
    // HIDE COLUMN
    private void cbHideColumn_Changed(object sender, RoutedEventArgs e)
    {
        CheckBox cb = sender as CheckBox;
        if (this.dataGrid1 != null)
        {
            if (cb.IsChecked == true)
                this.dataGrid1.Columns[0].Visibility = Visibility.Collapsed;
            else if (cb.IsChecked == false)
                this.dataGrid1.Columns[0].Visibility = Visibility.Visible;
        }
    }
    // SELECTION MODE
    private void cbSelectionMode_Changed(object sender, RoutedEventArgs e)
    {
        CheckBox cb = sender as CheckBox;
        if (this.dataGrid1 != null)
        {
            if (cb.IsChecked == true)
                this.dataGrid1.SelectionMode = DataGridSelectionMode.Single;
            else if (cb.IsChecked == false)
                this.dataGrid1.SelectionMode = DataGridSelectionMode.Extended;
        }
    }
    // COLUMN OPTIONS
    private void cbColReorder_Changed(object sender, RoutedEventArgs e)
    {
        CheckBox cb = sender as CheckBox;
        if (this.dataGrid1 != null)
            this.dataGrid1.CanUserReorderColumns = (bool)cb.IsChecked;
    }
    private void cbColResize_Changed(object sender, RoutedEventArgs e)
    {
        CheckBox cb = sender as CheckBox;
        if (this.dataGrid1 != null)
            this.dataGrid1.CanUserResizeColumns = (bool)cb.IsChecked;
    }
    private void cbColSort_Changed(object sender, RoutedEventArgs e)
    {
        CheckBox cb = sender as CheckBox;
        if (this.dataGrid1 != null)
            this.dataGrid1.CanUserSortColumns = (bool)cb.IsChecked;
    }
    // SCROLL BARS VISIBILITY
    private void cbVerticalScroll_Changed(object sender, RoutedEventArgs e)
    {
        CheckBox cb = sender as CheckBox;
        if (this.dataGrid1 != null)
        {
            if (cb.IsChecked == true)
                this.dataGrid1.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
            else if (cb.IsChecked == false)
                this.dataGrid1.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden;
            else 
                this.dataGrid1.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
        }
    }
    private void cbHorizontalScroll_Changed(object sender, RoutedEventArgs e)
    {
        CheckBox cb = sender as CheckBox;
        if (this.dataGrid1 != null)
        {
            if (cb.IsChecked == true)
                this.dataGrid1.HorizontalScrollBarVisibility = ScrollBarVisibility.Visible;
            else if (cb.IsChecked == false)
                this.dataGrid1.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden;
            else 
                this.dataGrid1.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
        }
    
    }
    // ROW BRUSH
    private void cbAltRowBrush_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ComboBoxItem cbi = ((ComboBox)sender).SelectedItem as ComboBoxItem;
    
        if (this.dataGrid1 != null)
        {
            if (cbi.Content.ToString() == "Custom")
                this.dataGrid1.AlternatingRowBackground = new SolidColorBrush(Color.FromArgb(255, 130, 175, 200));
            else if (cbi.Content.ToString() == "Default")
                this.dataGrid1.AlternatingRowBackground = new SolidColorBrush(Color.FromArgb(37, 233, 238, 244));
            else if (cbi.Content.ToString() == "Null")
                this.dataGrid1.AlternatingRowBackground = null;
        }
    }
    private void cbRowBrush_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ComboBoxItem cbi = ((ComboBox)sender).SelectedItem as ComboBoxItem;
        if (this.dataGrid1 != null)
        {
            if (cbi.Content.ToString() == "Custom")
                this.dataGrid1.RowBackground = new SolidColorBrush(Color.FromArgb(255, 135, 185, 195));
            else if (cbi.Content.ToString() == "Default")
                this.dataGrid1.RowBackground = new SolidColorBrush(Color.FromArgb(00, 255, 255, 255));
            else if (cbi.Content.ToString() == "Null")
                this.dataGrid1.RowBackground = null;
        }
    }
    // HEADERS VISIBILITY
    private void cbHeaders_SelectionChanged(object sender, RoutedEventArgs e)
    {
        ComboBoxItem cbi = ((ComboBox)sender).SelectedItem as ComboBoxItem;
        if (this.dataGrid1 != null)
        {
            if (cbi.Content.ToString() == "All")
                this.dataGrid1.HeadersVisibility = DataGridHeadersVisibility.All;
            else if (cbi.Content.ToString() == "Column (Default)")
                this.dataGrid1.HeadersVisibility = DataGridHeadersVisibility.Column;
            else if (cbi.Content.ToString() == "Row")
                this.dataGrid1.HeadersVisibility = DataGridHeadersVisibility.Row;
            else
                this.dataGrid1.HeadersVisibility = DataGridHeadersVisibility.None;
        }
    
    }
    // GRIDLINES VISIBILITY
    private void cbGridLines_SelectionChanged(object sender, RoutedEventArgs e)
    {
        ComboBoxItem cbi = ((ComboBox)sender).SelectedItem as ComboBoxItem;
        if (this.dataGrid1 != null)
        {
            if (cbi.Content.ToString() == "All")
                this.dataGrid1.GridLinesVisibility = DataGridGridLinesVisibility.All;
            else if (cbi.Content.ToString() == "Vertical (Default)")
                this.dataGrid1.GridLinesVisibility = DataGridGridLinesVisibility.Vertical;
            else if (cbi.Content.ToString() == "Horizontal")
                this.dataGrid1.GridLinesVisibility = DataGridGridLinesVisibility.Horizontal;
            else
                this.dataGrid1.GridLinesVisibility = DataGridGridLinesVisibility.None;
        }
    
    }
    // CUSTOM GRIDLINES
    private void cbCustomGridLineVert_Changed(object sender, RoutedEventArgs e)
    {
        CheckBox cb = sender as CheckBox;
        if (this.dataGrid1 != null)
        {
            if (cb.IsChecked == true)
                this.dataGrid1.VerticalGridLinesBrush = new SolidColorBrush(Colors.Blue);
            else 
                this.dataGrid1.VerticalGridLinesBrush = new SolidColorBrush(Color.FromArgb(255, 223, 227, 230));
        }
    }
    private void cbCustomGridLineHorz_Changed(object sender, RoutedEventArgs e)
    {
        CheckBox cb = sender as CheckBox;
        if (this.dataGrid1 != null)
        {
            if (cb.IsChecked == true)
                this.dataGrid1.HorizontalGridLinesBrush = new SolidColorBrush(Colors.Blue);
            else
                this.dataGrid1.HorizontalGridLinesBrush = new SolidColorBrush(Color.FromArgb(255, 223, 227, 230));
        }
    }
    
    
    
  3. 生成并运行此应用程序。

    当应用程序运行时,您将看到一个 DataGrid,其中显示 taskList 集合中的任务。 此外,您还将看到用于动态修改DataGrid 控件的外观和行为的选项。

  4. 当应用程序运行时,更改各个选项并查看对 DataGrid 控件的外观和行为产生的影响。

如果您无需在运行时动态设置 DataGrid 属性,则通常在 XAML 中设置这些属性。 若要查看 XAML 语法来设置属性,请参见DataGrid 属性文档的"XAML 属性用法"部分。

也可以通过向控件应用样式和模板来自定义 DataGrid。 利用样式和模板,可以对控件实现比设置属性更多的自定义。 若要了解有关如何向控件应用样式和模板的更多信息,请参见控件自定义和 DataGrid 样式和模板

原文地址:https://www.cnblogs.com/meimao5211/p/3413167.html