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;
        }
    }
}
相关推荐
我是苏苏8 小时前
C#基础:Winform桌面开发中窗体之间的数据传递
开发语言·c#
水果里面有苹果14 小时前
20-C#构造函数--虚方法
java·前端·c#
[纳川]17 小时前
把word中表格转成excle文件
开发语言·c#·word
lph197219 小时前
快速分页wpf
c#
试行20 小时前
C#System.Runtime.InteropServices.ExternalException (0x80004005): GDI+ 中发生一般性错误。
c#
❀always❀21 小时前
深入浅出分布式限流(更新中)
分布式·wpf
每日出拳老爷子1 天前
[C#] 使用TextBox换行失败的原因与解决方案:换用RichTextBox的实战经验
开发语言·c#
程序猿多布1 天前
C# 值拷贝、引用拷贝、浅拷贝、深拷贝
c#
阿蒙Amon1 天前
C#随机数生成全面详解:从基础到高级应用
服务器·网络·c#