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

2025浏览器指纹伪装终极指南:Playwright修改WebGL+时区+分辨率,小红书爬1000条零验证

2025年小红书的反爬已经进入“多维校验”时代,单纯修改某一个指纹维度已失效。本文方案的核心是“让所有特征都一致且合理”——WebGL+Canvas+时区+分辨率+UA+行为,形成一个完整的“真实用户画像”,让小红书的反爬系统无法区分是爬虫还是真人。这套方案不仅适用于小红书,也可迁移到知乎、抖音、跨境电商等其他高反爬平台,只需替换对应的指纹库和数据提取逻辑。记住:指纹伪装的本质不是“欺骗”,而是“模拟真实”,把每个细节都做到和人类一致,自然就能实现“零验证”爬取。

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 3071

GT-Power柴油机瞬态性能仿真与优化——基于EGR-VGT耦合控制策略【附案例】

本文探讨了GT-Power在柴油机瞬态性能仿真与优化中的应用,重点分析了EGR-VGT耦合控制策略的实际效果。通过案例研究展示了如何通过仿真优化提升柴油机的动力响应速度和排放性能,为车辆工程领域的工程师提供了实用的技术参考。

green的博客 763

WPF DataGrid数据绑定

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

L.的博客 1153

GAMES101:MacOS作业环境搭建

查看gcc/clang的位置产看gcc/clang的版本1.1.2 安装cmake。

weixin_38844255的博客 717

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

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

gitblog_09702的博客 998

PCB测试点

PCB测试点

qq_31444421的博客 1万+

计算图像哈希SHA-512

上述需要将lena.jpg放在当前目录下。

计算机视觉之光 961

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

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

gitblog_09789的博客 913

用Excel或WPS做两独立样本的T检验

一般情况下收集数据时常用的是Excel或者WPS,但统计时却用SPSS等软件进行统计学分析,经常很多人找不到SPSS的安装包,或者苦于正版激活或忘记教程,其实Excel或WPS自带函数就足够了,均数、标准差以及统计检验都是一个函数而已。解释:先做F检验,如果F>0.05就做T检验,Ttset里的数据为两组的数据的比较,结果如下。A组的均数计算 =AVERAGE(B2:B6)A组的标准差计算 =STDEV(B2:B6)B组的标准差计算=STDEV(B7:B19)分组 数值 A组均数 A组标准差 p值。

Mrrunsen的博客 6752

WPF之 DataGrid数据绑定

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

weixin_33910759的博客 443

ICC2:使用analyze_lib_cell_placement检查lib cell的pass rate

我正在「拾陆楼」和朋友们讨论有趣的话题,你⼀起来吧?在place之前需要使analyze_lib_cell_placement命令去检查lib cell在当前的site row/power plan/legalize设置的环境下能够正常place和legalize。下面分享一个脚本去报告pass rate低于2%的lib cell。

m0_61544122的博客 675

RAG系统中Reranker模型选型实战

本文详细介绍了RAG系统中Reranker模型选型实战,希望能对学习RAG的同学们有所帮助。 文章目录 1. 前言 2. 思路解析 3. 测评数据集构建 3.1 步骤一 3.2 步骤二 3.3 数据示例 3.4 总结 4. 实战代码 4.1 本地模型 4.2 使用第三方的Reranker模型API

herosunly的博客 17万+

WPF DataGrid 数据绑定

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

weixin_43623326的博客 1314

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

wpf datagrid 数据绑定

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

Mark 1402

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

上一篇: 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、付费专栏及课程。

余额充值