WPF 数据集合绑定到DataGrid、ListView或者其他列表控件

原文: WPF 数据集合绑定到DataGrid、ListView或者其他列表控件

需求描述

需要使用一个类似表格的控件,数据格式如下:

数据名称 数据标记 数据值选择
DataA true Kea(可选的值:Kea,Lau,Nuh)
DataB true Lau(可选的值:Kea,Lau,Nuh)
DataC true invalid(可选的值:invalid,valid)
DataD false invalid(可选的值:invalid,valid)
DataE true 0(可选的值:0,1,2,3,4,5,6)
DataF true 100(可选的值:0,20,40,60,80,100,120,140,160,180,200)
DataG true 3(可选的值:0,1,2,3,4,5,6)

需求分析

  • 界面实现分析:

    可以看出,我们的数据排列为:名称、标识和值。名称可以通过TextBlock之类的标签控件实现,标识可以使用CheckBox或者ToggleButton实现;最后的值典型的需要使用下拉列表框(ComboBoxListBox等)。

    能够实现以上布局的有:①表格(DataGrid);②列表(ListBoxListViewItemControl);③自定义控件布局(数据有限和确定的情况下可以考虑)。本次对前两种进行讨论。

    DataGrid具备行、列的形式,因此很容易想到。每列我们分别使用DataGridTextColumnDataGridCheckBoxColumnDataGridComboBoxColumn即可完成。

    列表典型的列结构,不伦我们使用哪种列表,都需要自定义一个数据模板,用以实现我们

  • 数据结构分析:

    我们数据其实非常有规律,可以将其结构定义如下:


  
  
  1. using System.Collections.Generic;
  2. using System.Collections.ObjectModel;
  3. using System.Windows.Controls;
  4. namespace Melphi.UiCore
  5. {
  6. /// <summary>
  7. /// ListViewsView.xaml 的交互逻辑
  8. /// </summary>
  9. public partial class ListViewsView : UserControl
  10. {
  11. public ListViewsView()
  12. {
  13. InitializeComponent();
  14. }
  15. private ObservableCollection<MelphiDataItem> melphiDataSource = new ObservableCollection<MelphiDataItem>();
  16. /// <summary>
  17. /// 数据源
  18. /// </summary>
  19. public ObservableCollection<MelphiDataItem> MelphiDataSource
  20. {
  21. get
  22. {
  23. return melphiDataSource;
  24. }
  25. set
  26. {
  27. melphiDataSource = value;
  28. }
  29. }
  30. }
  31. /// <summary>
  32. /// 数据项
  33. /// </summary>
  34. public class MelphiDataItem
  35. {
  36. /// <summary>
  37. /// 数据名称
  38. /// </summary>
  39. public string Name { get; set; }
  40. /// <summary>
  41. /// 数据标识
  42. /// </summary>
  43. public bool IsEnabled { get; set; }
  44. /// <summary>
  45. /// 设定值
  46. /// </summary>
  47. public string SelectedValue { get; set; }
  48. /// <summary>
  49. /// 设定值选定项集合
  50. /// </summary>
  51. public List< string> SelectionSource { get; set; }
  52. }
  53. }

稍做说明:每个数据项就是一个MelphiDataItem的实例,使用变化自动通知界面的集合ObservableCollection来存储所有的数据。

设计实现

  • 初始化数据

一般情况下,我们的数据获取来源一般由文件、服务器或者数据库获得,为了方便,这里就直接在程序里面定义了。


  
  
  1. public class MelphiDataService
  2.   {
  3.         /// <summary>
  4.         /// 模拟获取数据源
  5.         /// </summary>
  6.         /// <returns></returns>
  7.         public static ObservableCollection<MelphiDataItem> GetDataSource()
  8.       {
  9.            ObservableCollection<MelphiDataItem> melphiDatas = new ObservableCollection<MelphiDataItem>();
  10.            melphiDatas.Add( new MelphiDataItem()
  11.           {
  12.                Name = "DataA",
  13.                IsEnabled = true,
  14.                SelectedValue = "Kea",
  15.                SelectionSource = new List< string>() { "Kea", "Lau", "Nuh" }
  16.           });
  17.            melphiDatas.Add( new MelphiDataItem()
  18.           {
  19.                Name = "DataB",
  20.                IsEnabled = true,
  21.                SelectedValue = "Lau",
  22.                SelectionSource = new List< string>() { "Kea", "Lau", "Nuh" }
  23.           });
  24.            melphiDatas.Add( new MelphiDataItem()
  25.           {
  26.                Name = "DataC",
  27.                IsEnabled = true,
  28.                SelectedValue = "invalid",
  29.                SelectionSource = new List< string>() { "invalid", "valid" }
  30.           });
  31.            melphiDatas.Add( new MelphiDataItem()
  32.           {
  33.                Name = "DataD",
  34.                IsEnabled = true,
  35.                SelectedValue = "invalid",
  36.                SelectionSource = new List< string>() { "invalid", "valid" }
  37.           });
  38.            melphiDatas.Add( new MelphiDataItem()
  39.           {
  40.                Name = "DataE",
  41.                IsEnabled = false,
  42.                SelectedValue = "0",
  43.                SelectionSource = new List< string>() { "0", "1", "2", "3", "4", "5", "6" }
  44.           });
  45.             var listsource = new List< string>();
  46.             for ( int i = 0; i <= 200; i+= 20)
  47.           {
  48.                listsource.Add(i.ToString());
  49.           }
  50.            melphiDatas.Add( new MelphiDataItem()
  51.           {
  52.                Name = "DataF",
  53.                IsEnabled = true,
  54.                SelectedValue = "100",
  55.                SelectionSource = listsource
  56.           });
  57.            melphiDatas.Add( new MelphiDataItem()
  58.           {
  59.                Name = "DataG",
  60.                IsEnabled = true,
  61.                SelectedValue = "3",
  62.                SelectionSource = new List< string>() { "0", "1", "2", "3", "4", "5", "6" }
  63.           });
  64.             return melphiDatas;
  65.       }
  66.   }

在程序视图构造时获取数据,并将数据复制给我们界面绑定的数据源。


  
  
  1. public partial class ListViewsView : UserControl
  2. {
  3. public ListViewsView()
  4. {
  5. InitializeComponent();
  6. // 获取数据源
  7. MelphiDataSource = MelphiDataService.GetDataSource();
  8. }
  9. private ObservableCollection<MelphiDataItem> melphiDataSource = new ObservableCollection<MelphiDataItem>();
  10. /// <summary>
  11. /// 数据源
  12. /// </summary>
  13. public ObservableCollection<MelphiDataItem> MelphiDataSource
  14. {
  15. get
  16. {
  17. return melphiDataSource;
  18. }
  19. set
  20. {
  21. melphiDataSource = value;
  22. }
  23. }
  24. }

  
  
  1. using System.Collections.ObjectModel;
  2. using System.Windows.Controls;
  3. namespace Melphi.UiCore
  4. {
  5. /// <summary>
  6. /// DataGridsView.xaml 的交互逻辑
  7. /// </summary>
  8. public partial class DataGridsView : UserControl
  9. {
  10. public DataGridsView()
  11. {
  12. InitializeComponent();
  13. // 获取数据源
  14. MelphiDataSource = MelphiDataService.GetDataSource();
  15. }
  16. private ObservableCollection<MelphiDataItem> melphiDataSource = new ObservableCollection<MelphiDataItem>();
  17. /// <summary>
  18. /// 数据源
  19. /// </summary>
  20. public ObservableCollection<MelphiDataItem> MelphiDataSource
  21. {
  22. get
  23. {
  24. return melphiDataSource;
  25. }
  26. set
  27. {
  28. melphiDataSource = value;
  29. }
  30. }
  31. }
  32. }
  • 界面设计以及数据绑定

  • ListView

  
  
  1. <UserControl x:Class="Melphi.UiCore.ListViewsView"
  2. xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x= "http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:mc= "http://schemas.openxmlformats.org/markup-compatibility/2006"
  5. xmlns:d= "http://schemas.microsoft.com/expression/blend/2008"
  6. xmlns:local= "clr-namespace:Melphi.UiCore"
  7. mc:Ignorable= "d"
  8. d:DesignHeight= "450" d:DesignWidth= "800">
  9. <Grid>
  10. <WrapPanel>
  11. <StackPanel>
  12. <!-- 标题 -->
  13. <ListView HorizontalAlignment="Left"
  14. BorderBrush= "Black" BorderThickness= "1" Margin= "20 20 20 0" >
  15. <ListViewItem>
  16. <Border BorderBrush="Black" BorderThickness="1">
  17. <Grid Width="500" >
  18. <Grid.ColumnDefinitions>
  19. <ColumnDefinition Width="3*"/>
  20. <ColumnDefinition Width="*"/>
  21. <ColumnDefinition Width="1.5*"/>
  22. </Grid.ColumnDefinitions>
  23. <TextBlock Grid.Column="0" VerticalAlignment="Center" Text="Name"/>
  24. <Border Grid.Column="1">
  25. <TextBlock VerticalAlignment="Center" Text="IsEnabled"/>
  26. </Border>
  27. <TextBlock Grid.Column="2" VerticalAlignment="Center" Text="Value"/>
  28. </Grid>
  29. </Border>
  30. </ListViewItem>
  31. </ListView>
  32. <!-- 内容 -->
  33. <ListView HorizontalAlignment="Left"
  34. BorderBrush= "Black" BorderThickness= "1" Margin= "20 0 20 20"
  35. ItemsSource= "{Binding Path=MelphiDataSource,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}">
  36. <ListView.ItemTemplate>
  37. <DataTemplate>
  38. <Border BorderBrush="Black" BorderThickness="1">
  39. <Grid Width="500" >
  40. <Grid.ColumnDefinitions>
  41. <ColumnDefinition Width="3*"/>
  42. <ColumnDefinition Width="*"/>
  43. <ColumnDefinition Width="1.5*"/>
  44. </Grid.ColumnDefinitions>
  45. <TextBlock Grid.Column="0" VerticalAlignment="Center" Text="{Binding Name}"/>
  46. <Border Grid.Column="1">
  47. <!-- 使用 ToggleButton 会让程序更好看,或者你重新定义控件模板来实现自己想要的效果 -->
  48. <!--<ToggleButton IsChecked="{Binding IsEnabled}" HorizontalAlignment="Stretch"/>-->
  49. <CheckBox IsChecked="{Binding IsEnabled}" HorizontalAlignment="Stretch"/>
  50. </Border>
  51. <ComboBox Grid.Column="2" SelectedItem="{Binding SelectedValue}" ItemsSource="{Binding SelectionSource}" TextBlock.TextAlignment="Center" HorizontalAlignment="Stretch" >
  52. </ComboBox>
  53. </Grid>
  54. </Border>
  55. </DataTemplate>
  56. </ListView.ItemTemplate>
  57. </ListView>
  58. </StackPanel>
  59. </WrapPanel>
  60. </Grid>
  61. </UserControl>
  • DataGrid


  
  
  1. <UserControl x:Class="Melphi.UiCore.DataGridsView"
  2. xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x= "http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:mc= "http://schemas.openxmlformats.org/markup-compatibility/2006"
  5. xmlns:d= "http://schemas.microsoft.com/expression/blend/2008"
  6. xmlns:local= "clr-namespace:Melphi.UiCore"
  7. mc:Ignorable= "d"
  8. d:DesignHeight= "450" d:DesignWidth= "800">
  9. <Grid>
  10. <WrapPanel>
  11. <DataGrid HorizontalAlignment="Left" Margin="10"
  12. ItemsSource= "{Binding Path=MelphiDataSource,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"
  13. RowDetailsVisibilityMode= "VisibleWhenSelected"
  14. AutoGenerateColumns= "False">
  15. <DataGrid.RowDetailsTemplate>
  16. <DataTemplate>
  17. <Border BorderThickness="0" Padding="5">
  18. <StackPanel Orientation="Vertical">
  19. <StackPanel Orientation="Horizontal">
  20. <TextBlock Text="Tips: " VerticalAlignment="Center"/>
  21. <TextBlock Text="{Binding Description}" VerticalAlignment="Center"
  22. FontSize= "15" FontWeight= "Bold"/>
  23. </StackPanel>
  24. </StackPanel>
  25. </Border>
  26. </DataTemplate>
  27. </DataGrid.RowDetailsTemplate>
  28. <DataGrid.Columns>
  29. <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" />
  30. <!-- 使用 DataGrid 提供的列 -->
  31. <DataGridCheckBoxColumn Header="IsActive" Binding="{Binding Path=IsEnabled}"/>
  32. <!-- 使用自定义的列模板 -->
  33. <DataGridTemplateColumn Header="Temp">
  34. <DataGridTemplateColumn.CellTemplate>
  35. <DataTemplate>
  36. <ToggleButton IsChecked="{Binding Path=IsEnabled,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
  37. </DataTemplate>
  38. </DataGridTemplateColumn.CellTemplate>
  39. </DataGridTemplateColumn>
  40. <!-- 使用 DataGrid 提供的列,修改其样式满足我们的显示需要 -->
  41. <!-- 注意:直接对其进行数据绑定是没有效果,这是关键点 -->
  42. <DataGridComboBoxColumn Header="Value">
  43. <DataGridComboBoxColumn.EditingElementStyle>
  44. <Style TargetType="ComboBox">
  45. <Setter Property="ItemsSource" Value="{Binding Path=SelectionSource}" />
  46. <Setter Property="SelectedValue" Value="{Binding Path=SelectedValue}" />
  47. </Style>
  48. </DataGridComboBoxColumn.EditingElementStyle>
  49. <DataGridComboBoxColumn.ElementStyle>
  50. <Style TargetType="ComboBox">
  51. <Setter Property="ItemsSource" Value="{Binding Path=SelectionSource}" />
  52. <Setter Property="SelectedValue" Value="{Binding Path=SelectedValue}" />
  53. </Style>
  54. </DataGridComboBoxColumn.ElementStyle>
  55. </DataGridComboBoxColumn>
  56. </DataGrid.Columns>
  57. </DataGrid>
  58. </WrapPanel>
  59. </Grid>
  60. </UserControl>

注意:

1.使用DataGridComboBoxColumn作为数据列时,需要修改DataGridComboBoxColumnEditingElementStyleElementStyle,将我们数据绑定到这两个样式上的ItemsSourceSelectedValue上。如果直接绑定到DataGridComboBoxColumnItemsSourceSelectedValue上,我们的数据绑定是无效的。

2.DataGrid控件提供的列中,有一个非常方便的列控件——DataGridTemplateColumn。这个模板列控件可以按照我们的界面需求进行自定义界面样式和数据绑定。值得留意的是:DataGrid提供的默认列,如DataGridTextColumnDataGridCheckBoxColumnDataGridComboBoxColumn以及DataGridHyperlinkColumn在做数据绑定时,默认情况下数据绑定是双向更新的(数据模型<-->界面);但是DataGridTemplateColumn的默认绑定是单向的(数据模型-->界面),如果需要双向时,需要对绑定的数据 指定UpdateSourceTrigger,如下所示,而列表类的控件就没有这个细节。


  
  
  1. <!-- 使用自定义的列模板 -->
  2. <DataGridTemplateColumn Header="IsTemplate">
  3. <DataGridTemplateColumn.CellTemplate>
  4. <DataTemplate>
  5. <ToggleButton IsChecked="{Binding Path=IsEnabled,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
  6. </DataTemplate>
  7. </DataGridTemplateColumn.CellTemplate>
  8. </DataGridTemplateColumn>
  • 运行调试

总结

虽然完成之后觉得很简单没什么,但是我在最开始拿到需求到真正实现的过程中走了不少的弯路,从早上上班到下午3点才算解决。

现在回头,觉得自己之所以走弯路,主要的问题出现在对控件的不熟悉,其中DataGridDataGridComboBoxColumn数据绑定不成功耗费最多。其次是对自己定义的数据结构不信任,导致对数据结构的多次更换、重新实验。

还是列表控件拯救了我,相比DataGrid控件,自己对列表控件认识要更深一些(也许是他更简单一些吧),让我最终坚信我的数据结构没问题,"简单轻松"得完成了需求。

但是DataGrid控件确实是一个非常好的控件。我们可以看到他具备一些普通的列模板,虽然不能完全满足我们的需求。但是他提供了DataGridTemplateColumn列模板,我们可以根据我们的界面和数据需求进行自制模板。是不是很nice。不仅如此,该控件还提供了很多额外的功能,一般的编辑功能就不说了,还有选中提示功能如RowDetailsTemplate中定义了我们点击某一行时,的提示模板......总之,非常强,早学早轻松。

最后再说一点,在程序开发时,我们需要分析,尤其是对数据结构的分析,慢慢地你会得到极大提升。

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/12154743.html