转载地址:http://www.zhixing123.cn/net/csharp-wpf-datagrid-binding.html
最近使用C#+WPF开发一个小测试工具,其中用到了DataGrid。因为没有C#+WPF的开发经验也是一边摸索一边开发,所幸C#+WPF的上手难度不大,开发过程较为顺利。不过在使用DataGrid的时候还是遇到了一点阻绊,并且让人有些恼火。
闲话少叙,讲一下这里DataGrid应该怎么用,以及要注意的事情。
DataGrid是个非常实用的控件,可以用来展示及获取较为复杂的数据结构。
要在C#+WPF下使用DataGrid并绑定数据,大致操作如下:
1. 在资源视图xml文件中添加DataGrid,并设置绑定。
<DataGrid x:Name="DATA_GRID" ItemsSource="{Binding}" AutoGenerateColumns="False" Grid.Row="1">
<DataGrid.Columns>
<DataGridTextColumn Header="姓名" Binding="{Binding name}"/>
<DataGridTextColumn Header="年龄" Binding="{Binding age}"/>
<DataGridComboBoxColumn Header="性别" SelectedItemBinding="{Binding sexual}" ItemsSource="{Binding Source={StaticResource SexualEnum}}"/>
</DataGrid.Columns>
</DataGrid>
如果要让DataGridComboBoxColumn中下拉列表的内容为制定枚举类型的内容,则要指定静态资源。这样,整个xaml文件如下:
<Window x:Class="DataGridTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:core="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:DataGridTest"
Title="C# WPF DataGrid" Height="350" Width="525" Loaded="MainWindowLoaded">
<Window.Resources>
<ObjectDataProvider x:Key="SexualEnum" MethodName="GetValues" ObjectType="{x:Type core:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type Type="local:sexual_enum"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="36*"/>
<RowDefinition Height="283*"/>
</Grid.RowDefinitions>
<Label Content="DataGrid" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top"/>
<DataGrid x:Name="DATA_GRID" ItemsSource="{Binding}" AutoGenerateColumns="False" Grid.Row="1">
<DataGrid.Columns>
<DataGridTextColumn Header="姓名" Binding="{Binding name}"/>
<DataGridTextColumn Header="年龄" Binding="{Binding age}"/>
<DataGridComboBoxColumn Header="性别" SelectedItemBinding="{Binding sexual}" ItemsSource="{Binding Source={StaticResource SexualEnum}}"/>
</DataGrid.Columns>
</DataGrid>
<Button x:Name="BTN_CHK_DATA" Content="CheckData" HorizontalAlignment="Left" Margin="432,10,0,0" VerticalAlignment="Top" Width="75" Click="BTN_CHK_DATA_Click"/>
</Grid>
</Window>
2.在初始化代码中设置DataGrid绑定到的对象。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
namespace DataGridTest
{
public enum sexual_enum {
BOY,
GIRL
}
public class people
{
public string name;//{ get; set; }
public string age { get; set; }
public sexual_enum sexual { get; set; }
}
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
ObservableCollection<people> peopleList = new ObservableCollection<people>();
public MainWindow()
{
InitializeComponent();
}
private void MainWindowLoaded(object sender, RoutedEventArgs e)
{
peopleList.Add(new people(){
name="小明",
age="18",
sexual = sexual_enum.BOY,
});
peopleList.Add(new people()
{
name = "小红",
age = "18",
sexual=sexual_enum.GIRL
});
((this.FindName("DATA_GRID")) as DataGrid).ItemsSource = peopleList;
}
private void BTN_CHK_DATA_Click(object sender, RoutedEventArgs e)
{
string txt = "";
foreach (people peo in peopleList)
{
txt += peo.name;
txt += peo.age;
txt += peo.sexual.ToString();
txt += "\r\n";
}
MessageBox.Show(txt);
}
}
}
3. 运行效果如下。
其中,弹出框中为peopleList的数据。
修改dataGrid中的数据,然后再点checkData按钮,可以看到数据已经被修改。
非常需要注意的一点是,在定义people的类时,成员变量一定要有get和set,如果没写,会出现找不到绑定项的错误,如下:
比如,如果去掉people类中name的get和set,那么会报如下错误:
System.Windows.Data Error: 40 : BindingExpression path error: 'name' property not found on 'object' ''people' (HashCode=43794757)'. BindingExpression:Path=name; DataItem='people' (HashCode=43794757); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')
这个很血泪……切记……