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;
        }
    }
}
相关推荐
暗暗别做白日梦2 小时前
Pulsar 消息同步机制
c#·linq
海盗12342 小时前
微软技术周报——2026-07-22
microsoft·c#·.net
海盗12342 小时前
微软技术日报 ——2026-07-21
microsoft·c#·.net
-银雾鸢尾-2 小时前
C#中的泛型约束
开发语言·c#
WWJA王文举3 小时前
单片机参数如何掉电保存:Flash、EEPROM和配置存储完整设计
数据库·stm32·mongodb·c#
czhc11400756634 小时前
722:零侵入;DBG;
c#
-银雾鸢尾-13 小时前
C#中的StringBuilder相关方法
开发语言·c#
-银雾鸢尾-14 小时前
C#中结构体与类的区别;抽象类与接口的区别
开发语言·c#
心平气和量大福大17 小时前
C#-WPF-Window主窗体
开发语言·c#·wpf
白露与泡影18 小时前
Arthas 实战指南:从方法耗时定位到 JVM 变量热修改
服务器·jvm·c#