WPF使用DataGrid数据绑定

WPF DataGrid 数据绑定与组合框列实现


前言

在这里插入图片描述


一、新建数据模型

public class NotifyPropertyObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propertyName)
    {
        if(PropertyChanged != null)
        {
            PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }


}
public class MyStudent: NotifyPropertyObject
{
    private int _Num;

    public int Num
    {
        get { return _Num; }
        set { _Num = value;
            OnPropertyChanged("Num");
        }
    }

    private bool _IsTest;

    public bool IsTest
    {
        get { return _IsTest; }
        set { _IsTest = value;
            OnPropertyChanged("IsTest");
        }
    }


    private string _Name;

    public string Name
    {
        get { return _Name; }
        set { _Name = value;
            OnPropertyChanged("Name");
        }
    }

    private int _Age;

    public int Age
    {
        get { return _Age; }
        set { _Age = value;
            OnPropertyChanged("Age");
        }
    }

    private double _Score;

    public double Score
    {
        get { return _Score; }
        set { _Score = value;
            OnPropertyChanged("Score");
        }
    }

    private string _State; 

    public string State
    {
        get { return _State; }
        set { _State = value;
            OnPropertyChanged("State");
        }
    }

}

二、界面设计

<Window x:Class="WPFBindingDemo.MainWindow"
        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:WPFBindingDemo"
        mc:Ignorable="d"
        Title="MainWindow" Height="650" Width="800">
    	<Grid>
	        <Grid.Resources>
	            <!--Create list of enumeration values-->
	            <ObjectDataProvider x:Key="strList" 
	            ObjectType="{x:Type local:OSList}" 
	            MethodName="GetList"/>
	        </Grid.Resources>
	        <Grid.ColumnDefinitions>
	            <ColumnDefinition/>
	            <ColumnDefinition/>
	        </Grid.ColumnDefinitions>
	        <Grid.RowDefinitions>
	            <RowDefinition Height="auto"/>
	            <RowDefinition />
	        </Grid.RowDefinitions>
	        <Grid Grid.Column="1" Name="GridTable" Height="360" Background="Silver" Margin="2">
	            <Grid.RowDefinitions>	
	                <RowDefinition></RowDefinition>	
	                <RowDefinition></RowDefinition>	
	                <RowDefinition></RowDefinition>
	                <RowDefinition></RowDefinition>
	            </Grid.RowDefinitions>
	            <Grid.ColumnDefinitions>
	                <ColumnDefinition Width="130"></ColumnDefinition>
	                <ColumnDefinition Width="150"></ColumnDefinition>
	                <ColumnDefinition Width="20"></ColumnDefinition>
	            </Grid.ColumnDefinitions>
	            <Label Width="130" Height="25"  Grid.Row="0" Grid.Column="0"  Name="label1">TwoWay</Label>
	            <TextBox Width="150" Height="25"  Grid.Row="0" Grid.Column="1"  Name="textBox4" Text="{Binding ElementName=scrollBar1,Path=Value,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />
	            <Label Width="130" Height="25"  Grid.Row="1" Grid.Column="0"  Name="label2">OneWay</Label>	
	            <TextBox Width="150" Height="25"  Grid.Row="1" Grid.Column="1"   Name="textBox1" Text="{Binding ElementName=scrollBar1, Path=Value,Mode=OneWay}"/>	
	            <Label Width="130" Height="25"  Grid.Row="2" Grid.Column="0"  Name="label3">OneWayToSource</Label>	
	            <TextBox Width="150" Height="25"  Grid.Row="2" Grid.Column="1"   Name="textBox2" Text="{Binding ElementName=scrollBar1, Path=Value,Mode=OneWayToSource}" />	
	            <Label Width="130" Height="25"  Grid.Row="3" Grid.Column="0"  Name="label4">OneTime</Label> 	
	            <TextBox Width="150" Height="25"  Grid.Row="3" Grid.Column="1"   Name="textBox3" Text="{Binding ElementName=scrollBar1, Path=Value,Mode=OneTime}"/>
	            <ScrollBar Value="30" Minimum="0" Grid.RowSpan="4" Grid.Row="0" Grid.Column="3" Maximum="100" Name="scrollBar1" Width="18" Height="{Binding ElementName=GridTable,Path=Height}" />
	
        </Grid>

        <Grid Margin="2" Background="GreenYellow" Grid.Row="1" Grid.Column="1">
            <DataGrid x:Name="dataGridName" CanUserAddRows="False" AutoGenerateColumns="False" ItemsSource="{Binding MyStudentList,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" CanUserSortColumns="False">
                <DataGrid.Columns>
                    <DataGridCheckBoxColumn Header="选择" Width="*" Binding="{Binding IsTest}"></DataGridCheckBoxColumn>
                    <DataGridTextColumn Header="Num" Width="*" Binding="{Binding Num}"></DataGridTextColumn>
                    <DataGridTextColumn Header="Name" Width="*" Binding="{Binding Name}"></DataGridTextColumn>
                    <DataGridTextColumn Header="Age" Width="*" Binding="{Binding Age}"></DataGridTextColumn>
                    <DataGridTextColumn Header="Score" Width="*" Binding="{Binding Score}"></DataGridTextColumn>
                    <DataGridComboBoxColumn Header="State" Width="*" ItemsSource="{Binding Source={StaticResource strList}}" SelectedItemBinding="{Binding State}" TextBinding="{Binding State,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
                    </DataGridComboBoxColumn>
                    <DataGridComboBoxColumn Header="State" Width="*" ItemsSource="{x:Static local:StrList.StateList}" SelectedItemBinding="{Binding State}" TextBinding="{Binding State,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
                    </DataGridComboBoxColumn>
                   
                    <!--<DataGridTemplateColumn Header="Image" Width="SizeToCells" IsReadOnly="True">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Image Source="{Binding Image}" />
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>-->
                </DataGrid.Columns>
            </DataGrid>
        </Grid>
    </Grid>
</Window>
        

三、数据初始化

public class OSList
{
   string[] txList = new string[] { "1", "2", "3" };

   public string[] GetList()
   {
       return this.txList;
   }
}

public class StrList
{
   public static List<string> StateList { get; set; }

   static StrList()
   {
       StateList = new List<string>() { "1", "2", "3","4" };
   }
}

/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
   public ViewModels.MainViewModel ViewModel { get { return App.MainViewModel; } }

   public List<MyStudent> MyStudentList = new List<MyStudent>();

   public MainWindow()
   {
       InitializeComponent();

       this.DataContext = ViewModel;

       this.Loaded += MainWindow_Loaded;
   }

   private void MainWindow_Loaded(object sender, RoutedEventArgs e)
   {
       MyStudentList = new List<MyStudent>();

       for (int i = 0; i < 5; i++)
       {
           MyStudent myStudent = new MyStudent();
           myStudent.Num = i+1;
           myStudent.IsTest = true;
           myStudent.Name = "d" + i.ToString();
           myStudent.Age = i + 12;
           myStudent.Score = i + 78;
           myStudent.State = "1";
           MyStudentList.Add(myStudent);
       }

       dataGridName.ItemsSource = null;
       dataGridName.ItemsSource = MyStudentList;

   }

}

四、WPF DataGrid.DataGridComboBoxColumn 数据绑定

xaml代码:

<Grid>
    <Grid.Resources>
        <!--Create list of enumeration values-->
        <ObjectDataProvider x:Key="strList" 
            ObjectType="{x:Type local:OSList}" 
            MethodName="GetList"/>
    </Grid.Resources>
    <DataGrid Name="DG1" ItemsSource="{Binding}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridComboBoxColumn Header="下拉框测试"
               SelectedItemBinding="{Binding sIdx}" ItemsSource="{Binding Source={StaticResource strList}}">
            </DataGridComboBoxColumn>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

逻辑代码:

namespace DataBingTest
{
    /// <summary>
    /// DB_DataGrid.xaml 的交互逻辑
    /// </summary>
    public partial class DB_DataGrid : Window
    {
        public DB_DataGrid()
        {
            InitializeComponent();
 
            List<Info> infoList = new List<Info>();
 
            Info info02 = new Info();
            info02.sIdx = "1";
            infoList.Add(info02);
            info02 = new Info();
            info02.sIdx = "2";
            infoList.Add(info02);
            info02 = new Info();
            info02.sIdx = "3";
            infoList.Add(info02);
 
            DG1.DataContext = infoList;
        }
    }
 
    public class Info
    {
        public string sIdx { get; set; }
    }
 
    public class OSList
    {
        string[] txList = new string[] {"1" ,"2","3"};
 
        public string[] GetList()
        {
            return this.txList;
        }        
    }
}
 
<think>首先,用户正在询问有关在 WPF使用 DataGrid 数据绑定的信息,包括使用方法和示例。系统指令要求我使用中文回答,结构清晰,逐步解答问题,并尽量保证回答真实可靠。我还需要生成相关问题以结束回答。 我的回复需要包括: 1. 结构清晰:使用标题或小节组织内容。 2. 使用中文:全部内容用中文书写。 3. 数学表达式格式:如果用到数学,使用 $...$ 或 $$...$$,但这个问题可能不涉及数学,所以可能不需要。 4. 引用部分末尾添加引用标识:如 [^1], [^2], [^3]。 5. 生成相关问题:在回答结束时添加相关问题部分。 从引用中提取相关信息: - 引用 [1]:提到数据源可以是 DataTable 或 ObservableCollection<T>,并给出了一个简单的代码片段例子。 - 引用 [2]:描述 DataGrid 的优点,如格式化灵活、选择模型、编辑支持强大。 - 引用 [3]:提供了一个 GitHub 链接,可能包含示例代码,但由于是外部链接,我应该简化或描述它。 用户的问题是:“请问WPFDataGrid数据绑定使用方法和示例”。所以,我需要提供: - 解释什么是 DataGrid 数据绑定。 - 步骤或方法设置数据绑定。 - 代码示例演示如何使用。 组织回答结构: 1. **引言**:简要解释 WPF DataGrid 数据绑定。 2. **使用方法**:分步骤说明如何绑定数据源(如 ObservableCollection 或 DataTable)。 3. **示例**:提供代码片段展示绑定过程。 4. **注意事项或优点**:基于引用 [2],提及 DataGrid 的灵活性和编辑功能。 5. **引用标识**:在相关部分末尾添加 [^1], [^2], [^3]。 6. **生成相关问题**:结束时添加相关问题小节。 确保代码格式: - 代码块使用反引号或类似格式,如示例中所示。 - 在回复中,使用类似 Markdown 的格式。 具体内容: - **引言**:WPF DataGrid 是一个强大的控件,用于显示和编辑数据,支持数据绑定到不同的数据源。 - **使用方法**: - 步骤1:定义数据源(如 ObservableCollection<T>)。 - 步骤2:在 XAML 中设置 DataGrid 的 ItemsSource 属性绑定到数据源。 - 步骤3:定义列(如 DataGridTextColumn)。 - 步骤4:实现 INotifyPropertyChanged 以支持双向绑定(如果需要)。 - **示例**:基于引用 [1] 和 [3],提供一个简单示例。 - 创建一个 ObservableCollection<student>。 - 在 XAML 绑定。 - **注意事项**:强调 DataGrid 的灵活性,如格式化、选择模型 [^2]。 添加引用: - 在解释部分末尾添加 [^1], [^2], [^3]。 生成相关问题: - 例如: 1. 如何在 DataGrid 中实现双向数据绑定? 2. DataGrid 的列自定义方法是什么? 3. 如何处理 DataGrid 中的编辑事件? 最终结构: 1. WPF DataGrid 数据绑定简介 2. 使用方法 3. 示例代码 4. 优点和注意事项 5. §§相关问题§§ </think>### WPFDataGrid数据绑定使用方法和示例 在WPF中,DataGrid控件是实现表格数据展示和编辑的核心元素,支持强大的数据绑定功能。通过绑定数据源(如ObservableCollection<T>或DataTable),开发者可以高效实现数据的双向同步、格式化和编辑[^2]。以下是详细的使用方法和代码示例,基于引用内容整理。 #### 使用方法 DataGrid数据绑定的关键步骤包括: 1. **定义数据源**:使用ObservableCollection<T>(适用于动态更新)或DataTable(来自数据库或数据集)。 2. **设置绑定**:在XAML中将DataGrid的ItemsSource属性绑定到数据源。 3. **配置列**:定义列类型(如DataGridTextColumn)并绑定到数据源的属性。 4. **启用通知**:确保数据源实现INotifyPropertyChanged接口以支持双向绑定和数据实时更新。 DataGrid的优势在于其灵活的格式化能力、支持多行/单元格选择以及强大的编辑功能,适用于复杂数据编辑场景[^2]。 #### 示例:绑定ObservableCollection<T> 下面是一个完整的WPF示例,展示如何将DataGrid绑定到一个ObservableCollection<student>数据源。此示例基于引用[1]和[3]的简化实现。 **步骤1: 定义数据模型类(C#)** 在代码后置文件(如MainWindow.xaml.cs)中定义模型类: ```csharp using System.Collections.ObjectModel; using System.ComponentModel; public class Student : INotifyPropertyChanged { private string _name; private int _age; public string Name { get { return _name; } set { _name = value; OnPropertyChanged(nameof(Name)); } } public int Age { get { return _age; } set { _age = value; OnPropertyChanged(nameof(Age)); } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public partial class MainWindow : Window { public ObservableCollection<Student> Students { get; set; } public MainWindow() { InitializeComponent(); Students = new ObservableCollection<Student> { new Student { Name = "张三", Age = 20 }, new Student { Name = "李四", Age = 22 } }; DataContext = this; // 设置数据上下文 } } ``` **步骤2: 在XAML中配置DataGrid** 在XAML文件(如MainWindow.xaml)中绑定DataGrid: ```xml <Window x:Class="WpfApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="DataGrid绑定示例" Height="300" Width="400"> <Grid> <DataGrid ItemsSource="{Binding Students}" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTextColumn Header="姓名" Binding="{Binding Name}" /> <DataGridTextColumn Header="年龄" Binding="{Binding Age}" /> </DataGrid.Columns> </DataGrid> </Grid> </Window> ``` **说明**: - **动态更新**:ObservableCollection自动通知UI数据变化,无需手动刷新。 - **编辑功能**:用户可直接在DataGrid中修改数据,模型通过PropertyChanged事件同步更新。 - **更多示例**:引用[3]提供了GitHub上的进阶例子,包括多数据源绑定和事件处理。 #### 注意事项 - **绑定类型**:优先使用ObservableCollection<T>处理动态数据,DataTable适合静态数据集[^1]。 - **性能优化**:大数据量时启用虚拟化(EnableRowVirtualization="True")。 - **错误处理**:确保绑定路径正确,避免System.NullReferenceException。 通过上述方法,您可以高效实现WPF DataGrid数据绑定,适用于数据管理应用、报表系统等场景[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BeanGo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值