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;
        }
    }
}
相关推荐
电商api接口开发3 小时前
ASP.NET MVC 入门指南
c#·asp.net·mvc
我不是程序猿儿4 小时前
[C#]反射的实战应用,实际数据模拟
开发语言·c#
爱编程的鱼5 小时前
C# 结构(Struct)
开发语言·人工智能·算法·c#
是阿根5 小时前
unity使用iTextSharp生成PDF文件
unity·c#·游戏引擎
ABAP 成7 小时前
.NET Framework 4.0可用EXCEL导入至DataTable
c#
WineMonk9 小时前
C#多线程访问资源
c#
Bardb9 小时前
04-stm32的标准外设库
stm32·c#
风,停下10 小时前
C#基于Sunnyui框架和MVC模式实现用户登录管理
设计模式·c#·mvc
钢铁男儿10 小时前
C# 实战_RichTextBox选中某一行条目高亮,离开恢复
开发语言·c#
千叶真尹12 小时前
【无标题】
c#·linq