wpf datagrid 实现双向绑定

前台

csharp 复制代码
<DataGrid
    AutoGenerateColumns="False"
    Background="White"
    CanUserAddRows="True"
    Grid.Row="1"
    RowEditEnding="DataGrid_OnRowEditEnding"
    RowHeight="60"
    SelectionUnit="CellOrRowHeader"
    x:Name="DataGrid">


<!-- Mode=TwoWay, UpdateSourceTrigger=PropertyChanged  这两个设置很重要,没有的话无法实现双向绑定-->
    <DataGrid.Columns>
        <DataGridTextColumn
            Binding="{Binding ZhuJieNeiRong, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
            Header="注解内容"
            Width="*">
            <DataGridTextColumn.ElementStyle>
                <Style TargetType="TextBlock">
                    <Setter Property="VerticalAlignment" Value="Center" />
                </Style>
            </DataGridTextColumn.ElementStyle>

<!-- -->
<!-- 这里的功能是 如果设定了行高,加上这个样式 编辑表格时 内容是一直垂直居中-->
            <DataGridTextColumn.EditingElementStyle>
                <Style TargetType="TextBox">
                    <Setter Property="VerticalContentAlignment" Value="Center" />
                </Style>
            </DataGridTextColumn.EditingElementStyle>
        </DataGridTextColumn>
    </DataGrid.Columns>


</DataGrid>

后台

csharp 复制代码
public static ObservableCollection<Zjwz> _gridZhuJieList = new ObservableCollection<Zjwz>();

private void win_OnLoaded(object sender, RoutedEventArgs e)
{
    DataGrid.ItemsSource = _gridZhuJieList;
}

数据对象

csharp 复制代码
public class Zjwz : NotificationObject
{
    private string _zhuJieNeiRong;

    public string ZhuJieNeiRong
    {
        get { return _zhuJieNeiRong; }
        set
        {
            _zhuJieNeiRong = value;
            RaisePropertyChanged();
        }
    }
}

数据对象需要的类

csharp 复制代码
using System.Collections.Generic;
using System.ComponentModel;

namespace CommonSql
{
    public class NotificationObject : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void RaisePropertyChanged( string propertyName = null)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        
        protected virtual bool SetProperty<T>(ref T member, T value,  string propertyName = null)
        {
            if (EqualityComparer<T>.Default.Equals(member, value))
            {
                return false;
            }
            member = value;
            RaisePropertyChanged(propertyName);
            return true;
        }
    }
}
相关推荐
kylezhao20191 天前
第1章:第一节 开发环境搭建(工控场景最优配置)
开发语言·c#
钰fly1 天前
C#文件与数据操作核心概念手册
c#
阿蒙Amon1 天前
C#每日面试题-简述C#访问修饰符
windows·microsoft·c#
Kiyra1 天前
WebSocket vs HTTP:为什么 IM 系统选择长连接?
分布式·websocket·网络协议·http·设计模式·系统架构·wpf
酩酊仙人1 天前
ABP+Hangfire实现定时任务
后端·c#·asp.net·hangfire
阿蒙Amon1 天前
C#每日面试题-属性和特性的区别
java·面试·c#
要记得喝水1 天前
某公司C#-WPF面试题-来自nowcoder(含答案和解析)--2
c#·wpf
Joker 0071 天前
Linux nohup命令实战指南
linux·运维·wpf
爱敲点代码的小哥1 天前
类型转换 递归算法 编译错误 装箱和拆箱 知识点
开发语言·c#
时光追逐者2 天前
一个 WPF 开源、免费的 SVG 图像查看控件
开源·c#·.net·wpf