WPF - INotifyPropertyChanged 到父数据 - 不会在从复选框更改值时触发

问题描述 投票:0回答:1

我有一个显示项目列表的 DataGrid

每行都有一个复选框,应更改相应数据类中的布尔字段

  • 我希望字段值发生变化并触发 OnPropertyChanged

  • 应用程序初始化时,设置器在列表初始化时被触发

  • 当我单击任何复选框时,设置器永远不会触发

这是控制xaml:

<DataGrid x:Name="ModificationsGrid" AutoGenerateColumns="False" ItemsSource="{Binding Value}"  >
    <DataGrid.Columns>

        <DataGridTemplateColumn Header="Action">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <CheckBox IsChecked="{Binding Enabled, Mode=TwoWay}" VerticalAlignment="Center"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

    </DataGrid.Columns>
</DataGrid>

对应的Data类

using System.ComponentModel;

namespace MyNameSpace.refactor
{
    // Refactor operation data
    public class RefactorOperation : INotifyPropertyChanged
    {
        public RefactorOperation(int startLine, int startChar, int endLine, int endChar, string[] content, bool enabled)
        {
            StartLine = startLine;
            StartCharacter = startChar;
            EndLine = endLine;
            EndCharacter = endChar;
            Content = content;
            Enabled = enabled;
        }

        public int StartLine { get; set; }
        public int StartCharacter { get; set; }
        public int EndLine { get; set; }
        public int EndCharacter { get; set; }
        public string[] Content { get; set; }

        private bool _enabled; // field related to below property
        public bool Enabled
        {
            get { return _enabled; }
            set
            {   
                // should trigger on chekcbox interactions
                _enabled = value;
                OnPropertyChanged(nameof(Enabled)); 
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

我错过了什么吗?

感谢您的帮助

wpf inotifypropertychanged
1个回答
0
投票

添加

UpdateSourceTrigger=PropertyChanged

到您的 CheckBox IsChecked 数据绑定。默认为 LostFocus,它要求您在更新绑定属性值之前将焦点切换到不同的控件。

© www.soinside.com 2019 - 2024. All rights reserved.