【问题标题】:C# WPF DataGrid Save changes - Binding ClassesC# WPF DataGrid 保存更改 - 绑定类
【发布时间】:2022-12-17 07:21:29
【问题描述】:

目前我正在尝试从 WPF 中的 Datagrid 获取新值,在本例中为 CheckBox 并导出它或其他任何内容。不幸的是,我的情况没有任何效果。

我有一个带有 DataGridTemplateColumn 的 DataGrid,最后有一个 CheckBox。该值绑定到布尔变量。

现在我希望用户更改值(例如取消选中 CheckBox)并保存该值。

XAML:

<DataGridTemplateColumn Header="Export?" Width="100">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate >
                            <CheckBox Margin="20, 0" IsChecked="{Binding toExport}"/>

当我导出 DataGrid 中的所有项目时,仅导出初始项目的旧值。我尝试使用 CellEditingTemplate,但未显示任何值。我究竟做错了什么?

<DataGridTemplateColumn Header="Test">
                    <DataGridTemplateColumn.CellEditingTemplate>
                        <DataTemplate>
                            <CheckBox Margin="20, 0" IsChecked="{Binding toExport}"/>

我真的试图在互联网上找到解决方案,但不幸的是我找不到任何线索。有什么地方我可能忽略了信息吗?

非常感谢你 :)

【问题讨论】:

    标签: wpf checkbox data-binding datagrid save


    【解决方案1】:

    听起来您正在尝试在用户修改 DataGrid 中的 CheckBox 时更新数据对象中 toExport 属性的值,但未保存更改。

    一个可能的问题是您没有在数据对象中实现 INotifyPropertyChanged 接口。此接口允许对象在属性值更改时发出通知,以便可以更新 UI 以反映新值。

    要实现 INotifyPropertyChanged 接口,您需要向数据对象添加一个名为 PropertyChanged 的事件,并在属性值更改时引发此事件。以下是如何执行此操作的示例:

    public class MyDataObject : INotifyPropertyChanged
    {
        private bool _toExport;
        public bool toExport
        {
            get { return _toExport; }
            set
            {
                _toExport = value;
                OnPropertyChanged("toExport");
            }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
    

    您还需要将 DataGrid 的 DataContext 设置为数据对象的一个​​实例,以便绑定可以正常工作。

    <DataGrid ItemsSource="{Binding MyDataObjectList}" AutoGenerateColumns="False">
        <DataGridTemplateColumn Header="Export?" Width="100">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate >
                    <CheckBox Margin="20, 0" IsChecked="{Binding toExport}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid>
    
    MyDataObject dataObject = new MyDataObject();
    dataObject.toExport = true;
    
    DataGrid.DataContext = dataObject;
    

    这应该允许 UI 在 toExport 属性更改时正确更新,并且更改应保存在数据对象中。

    亲切的问候 约翰·斯特普

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-19
      • 2016-10-07
      • 1970-01-01
      • 2010-12-24
      • 1970-01-01
      • 2017-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多