WPF使用DataGrid数据绑定

WPF Datagrid绑定数据 datagrid绑定属性如下(已实现INotifyPropertyChanged),对List<T>进行赋值,会刷新绑定,但是对T(未实现INotifyPropertyChanged)进行赋值,不会刷新绑定。要想T发生变更时刷新绑定,需要对T实现INotifyPropertyChanged。要想T中属性A根据T中属性B变化而变化,还要在B赋值时刷新A数据。 阅读详情


前言

在这里插入图片描述


一、新建数据模型

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;
        }        
    }
}
 
WPF DataGrid实现对SelectedItems的绑定 上面的DataGrid多选选中的项能实时体现到下面的DataGrid,并且点击按钮能选中上面成绩>85的学生,下面的DataGrid也能修改,在不用后置代码也就是不获取DataGrid这个对象的方式完成,那么我就想到用SelectedItems双向绑定了,那么我们现在就来完成它。SelectedItems并不是依赖属性,所以按道理来说我们是不能对其进行绑定的,那么我们只能自己定义依赖属性或者附加属性来实现,这边我是用的附加属性来实现的。我们需要在Model中加一个是否选中的属性。 阅读详情

相关推荐

一起搭WPF之列表数据绑定

之前已经简单介绍了列表的大致设计,在设计完列表界面后,我们可以开展列表的数据绑定,在前端显示我们的数据,对列表进行数据输入。那么让我们开始大干一场吧!例如:以上就是今天要讲的内容,本文仅仅简单介绍了列表数据的绑定。

arriettyandray的博客 1796

WPF之DataGrid的使用及案例

有四种列形式,如下图text用于显示文本框,checkBox显示多选框,Combox复选框,hyperLink超链接。除去默认的控件以外,还支持自定义单元格,使用​,如图,我在白表格中添加了一个按钮用于修改数据。​​。

m0_59871062的博客 4158

Wpf DataGrid的数据绑定

在项目开发的过程,通常会遇到一些表格数据的绑定,因为没有WPF的开发经验所以一边摸索一边开发,所幸WPF的上手难度不大,开发过程较为顺利。不过在使用DataGrid的时候还是遇到了一点阻绊遇。所以在这里讲一下这个DataGrid应该怎么用,以及要注意的事情。 DataGrid是个非常实用的控件,可以用来展示及获取较为复杂的数据结构。 要在WPF下使用DataGrid并绑定数据,大致操作如下: 1、在资源视图xml文件中添加DataGrid,并设置绑定,如下。 <Windowx:Class=".

weixin_44541250的博客 7638

WPF DataGrid与数据绑定

WPF DataGrid与数据绑定 MVVM基础 using System.ComponentModel; using System.Runtime.CompilerServices; namespace Melphi.Mvvm.Base { /// <summary> /// ViewModel模型基类(属性更改通知) /// A base class fo...

YouyoMei的博客 1796

WPF入门(四)-WPF+LINQ实现数据绑定、交互及简单datagrid样式

<br />本事例是基于WPF+LINQ实现的,先上效果图:<br /> <br /><br /> <br />要实现这个效果,首先要做的操作肯定是绑定数据,下面是LINQ生成的数据表关系图:<br /> <br /><br /> <br />创建数据上下文<br /> <br />WPFDataDataContext db = new WPFDataDataContext(); <br /> <br />在XAML界面,使用了两个控件,ComboBox与DataGrid,下面先实现数据的绑定,通过下拉菜单

wuyoulang的专栏 4089

WPF中基于MVVM的DataGrid数据绑定与命令交互实战

setset考虑如下需求:每行包含“编辑”和“查看日志”两个按钮,分别调用不同命令。<DataGridTemplateColumn Header="操作"><Button Content="编辑"<Button Content="日志"这里再次使用突破作用域限制。另一种方式是使用绑定命名控件:两者效果相同,但更适合控件树深层嵌套,则更清晰易读。该项目体现出多个 WPF 工程级设计亮点:松耦合通信机制:通过命令与绑定解耦 UI 事件处理;

weixin_32456485的博客 1191

WPF Datagrid 动态生成列 并绑定数据

说的是这里 因为列头是动态加载的 (后台for循环 一会能看到代码) 数据来源于左侧列 左侧列数据源 当然num1 属于临时的dome使用 可以用ObservableCollection集合代表 动态创建属性 WPF 动态生成对象属性 (dynamic) ObservableCollection<NameList> listName = new O...

时意 8873

WPF实现DataGrid嵌入ComBox绑定

WPF .Net6 实现DataGrid嵌入ComBox绑定 通过绑定实现报表内容通过ComBox实现

WPF DataGrid MVVM模式数据绑定

WPF DataGrid MVVM模式数据绑定 1、创建Model public class User { public int Id { get; set; } public string Name { get; set; } public char Sex { get; set; } public int Age { get; set; } public string Memo { get; set; }

manlibj的博客 5769

USB2.0学习1--基本概念

USB全称是 Universal Serial Bus,即通用串行总线,是一种计算机与外围设备进行数据交互的串行通信标准。USB协议是在1994年底由英特尔、IBM、Microsoft等公司联合提出的,现由USB协会(USB-IF)管理。USB使用差分信号来传输数据,具有传输速度快、支持热插拔、连接灵活、独立供电、协议向下兼容等优点,目前应用十分广泛。

原海青木的博客 3762

【论文笔记】Reaching agreement in the presence of faults (EIG)

1 问题定义 2 交互一致性 3 单点故障 m=1 n=4 4 多点故障(n&amp;gt;=3m+1) 计算过程 m=2 n=7 5 n&amp;lt;3m+1不能达成协定 6 带认证的算法 7 总结 这篇论文在1980年发表,是1982年著名的拜占庭将军问题论文的前身。作者Leslie Lamport是2013图灵奖得主,两篇论文引用次数分别为5000+和2000+。该论文提出的算法现在被...

zjwreal 2994

WPF DataGrid数据绑定

后台数据绑定 用户场景是生成报表,展示公司各员工每个月的绩效 数据结构 包括报表和单个员工绩效两个实体 public class Report { /// <summary> /// 统计时间 /// </summary> public string StatisticalDate { get; set; } public List<ReportDetail> ReportDetails { get; set; } } publi

L.的博客 1153

FAST_LIO_ROS2 可以用gazebo仿真吗?

摘要:FAST_LIO_ROS2可与Gazebo仿真环境兼容,通过订阅Gazebo模拟的激光雷达和IMU数据实现SLAM建图。已有开源项目(如pb_rm_simulation)验证了该方案,支持导航模式切换与真实机器人移植。关键步骤包括环境配置、传感器话题匹配及参数调试,需注意版本兼容性与数据噪声处理。相关教程提供了从环境搭建到三维建图的完整流程。

专注 激光SLAM, 目标检测, 欢迎关注, 分享交流! 1138

【亲测免费】 WPF DataGrid 每行不同 ComboBox 数据绑定教程

WPF DataGrid 每行不同 ComboBox 数据绑定教程 去发现同类优质开源项目:https://gitcode.com/ 本资源文件详细介绍了如何在 WPF 的 DataGrid 中为每一行设置不同的 ComboBox 数据绑定。通过本教程,你将学会如何实现 DataGrid 的 ItemSource 绑定,并为每个 ComboBox 单独设置 ItemSource,实现类似两次映射的...

gitblog_09702的博客 998

【电路设计】带阻滤波器实战:从理论到Twin-T陷波电路实现

本文详细介绍了带阻滤波器的原理与Twin-T陷波电路的实战应用,从基础概念到工程实现全面解析。通过具体案例展示如何设计高Q值滤波器,解决电源噪声等实际问题,并分享PCB布局和元件选型的实用技巧,助力工程师提升电路设计能力。

gg901的博客 1022

Scipy优化踩坑实录:trust-constr和SLSQP约束定义到底差在哪?

本文深入解析了Scipy优化模块中trust-constr和SLSQP两种方法在约束定义上的差异。通过对比面向对象的trust-constr和字典式定义的SLSQP,揭示了它们各自的优势与适用场景,帮助开发者在有约束优化问题中选择合适的算法,提升计算效率与准确性。

weixin_42573113的博客 271

掌握WPF DataGrid中每行不同ComboBox数据绑定的终极指南

掌握WPF DataGrid中每行不同ComboBox数据绑定的终极指南 去发现同类优质开源项目:https://gitcode.com/ 项目介绍 在现代桌面应用程序开发中,WPF(Windows Presentation Foundation)凭借其强大的数据绑定和UI定制能力,成为了众多开发者的首选框架。然而,当涉及到在DataGrid中为每一行设置不同的ComboBox数据绑定时,许多开发...

gitblog_09789的博客 913

企业微信消息推送(一)接收消息服务器URL

企业微信限制过多,公司域名所有权检验不通过。采用接收消息服务器URL的方式。使用vscode,将UTF-8 BOM文本编码改为UTF-8。配置接收消息服务器URL。

Xiaoweidumpb 1万+

WPF之 DataGrid数据绑定

DataGrid控件是显示数据的控件,从一个对象集合获取信息并在具有行和单元格的网格中显示信息。每行和一个单独的对象相对应,并且每列和该对象中的一个属性相对应。 DataGrid控件添加了许多在WPF中处理数据所需要的技能。其基于列的模型提供了显著的格式化灵活性,其选择模型允许选择一行,多行或一些单元格的组合,其编辑支持非常强大,可以使用DataGrid控件作为简单数据和复杂数据的统一数...

weixin_33910759的博客 443

RK35X8调试YT8531单网口千兆以太网PHY芯片,修复ping不通或者IP地址丢失的问题

RK35X8上调试YT8531以太网PHY

荻夜的博客 3976

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

WPF DataGrid 数据绑定

DataGridTextColumn Header="编号" Binding="{Binding Id}" Width="100" Visibility="Hidden"/>

weixin_43623326的博客 1314

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

wpf datagrid 数据绑定

wpf datagrid 数据绑定:  需要做两个步:      (1) 在设计页面为每一个列:设置binding属性:如Binding={Binding Name}      (2)在代码页面为datagrid设置itemsource属性:如this.datagrid1.itemsource=userinfroObjectList;

Mark 1402

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

上一篇: WPF的数据绑定
下一篇: drawing.Image转换为System.Windows.Media.ImageSource即WPF中使用的图片Source
BeanGo
博客等级 码龄10年 931粉丝 167原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

打赏作者

BeanGo

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

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

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

打赏作者

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

抵扣说明:

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

余额充值