WPF中提供xaml文件跟後臺的C#代碼數據交換的一種新的方式,那就是Binding。流程如下:
1、定義相應的類
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfApp1
{
class student
{
public string name { get; set; }
public string ID { get; set; }
}
}
2、在xaml文件中Binding相應的屬性,代碼中的name,ID均爲類中的屬性值
<Window x:Class="WpfApp1.Window2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="Window2" Height="450" Width="800">
<Grid>
<StackPanel Margin="5" Orientation="Horizontal">
<DataGrid Name="datagrid" AutoGenerateColumns="False" CanUserAddRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" MinWidth="60" Binding="{Binding name}"/>
<DataGridTextColumn Header="age" MinWidth="60" Binding="{Binding ID}"/>
</DataGrid.Columns>
</DataGrid>
<Button Name="button1" Content="ok" VerticalAlignment="Top" Margin="5" Click="Button1_Click"/>
</StackPanel>
</Grid>
</Window>
3、在後臺的C#代碼中定義動態集合,指明Binding的源,增加數據到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.Shapes;
using System.Collections.ObjectModel;
namespace WpfApp1
{
/// <summary>
/// Window2.xaml 的交互邏輯
/// </summary>
public partial class Window2 : Window
{
ObservableCollection<student> studentlist = new ObservableCollection<student>();
public Window2()
{
InitializeComponent();
datagrid.ItemsSource = studentlist; //將datagrid的源Binding到studentlist
}
private void Button1_Click(object sender, RoutedEventArgs e)
{
Random rd = new Random();
studentlist.Add(new student() //增加datagrid數據
{
name = "chris",
ID = Convert.ToString(rd.Next(1000, 2000)),
});
}
}
}