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;
        }
    }
}
相关推荐
玩泥巴的6 小时前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21888 小时前
.NET 本地Db数据库-技术方案选型
windows·c#
lindexi10 小时前
dotnet DirectX 通过可等待交换链降低输入渲染延迟
c#·directx·d2d·direct2d·vortice
qq_4542450312 小时前
基于组件与行为的树状节点系统
数据结构·c#
bugcome_com13 小时前
C# 类的基础与进阶概念详解
c#
雪人不是菜鸡13 小时前
简单工厂模式
开发语言·算法·c#
铸人13 小时前
大数分解的Shor算法-C#
开发语言·算法·c#
未来之窗软件服务14 小时前
AI人工智能(二十四)错误示范ASR张量错误C#—东方仙盟练气期
开发语言·人工智能·c#·仙盟创梦ide·东方仙盟
yong999014 小时前
基于C#实现的UPnP端口映射程序
开发语言·c#
三天不学习14 小时前
Linux inotify 机制详解,解决“用户实例限制”问题
linux·运维·c#