C# WPF中DataGrid的数据绑定(Binding)

转载地址: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')

这个很血泪……切记……

以下是WPFDataGrid和Excel绑定的代码示例。 首先,需要在XAML文件添加DataGrid控件: ```xml <DataGrid x:Name="myDataGrid" ItemsSource="{Binding}"> <DataGrid.Columns> <DataGridTextColumn Header="姓名" Binding="{Binding Name}" /> <DataGridTextColumn Header="年龄" Binding="{Binding Age}" /> <DataGridTextColumn Header="性别" Binding="{Binding Gender}" /> </DataGrid.Columns> </DataGrid> ``` 然后,在C#代码,需要添加以下引用: ```csharp using Excel = Microsoft.Office.Interop.Excel; ``` 接着,需要定义一个类来存储Excel数据: ```csharp public class Person { public string Name { get; set; } public int Age { get; set; } public string Gender { get; set; } } ``` 然后,需要添加以下代码来读取Excel文件数据: ```csharp Excel.Application excelApp = new Excel.Application(); Excel.Workbook workbook = excelApp.Workbooks.Open(@"C:\path\to\your\excel\file.xlsx"); Excel.Worksheet worksheet = workbook.Sheets[1]; Excel.Range range = worksheet.UsedRange; List<Person> people = new List<Person>(); for (int row = 2; row <= range.Rows.Count; row++) { Person person = new Person(); person.Name = Convert.ToString((range.Cells[row, 1] as Excel.Range).Value2); person.Age = Convert.ToInt32((range.Cells[row, 2] as Excel.Range).Value2); person.Gender = Convert.ToString((range.Cells[row, 3] as Excel.Range).Value2); people.Add(person); } myDataGrid.ItemsSource = people; ``` 最后,需要记得在程序结束时关闭Excel应用程序: ```csharp workbook.Close(); excelApp.Quit(); ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值