更新与BindingList关联的DataGrid

时间:2019-01-21 10:44:47

标签: c# wpf datagrid

我正在尝试更新DataGrid中的数据。它与BindingList相关联。我尝试从ObservableCollection开始,但是没有刷新更新数据的能力。我需要一个选项,当我更改给定行中的值时,其他选项将依赖于其他选项,并且必须自动更新。

下面的代码无法正常工作。我会忘记什么吗?

ViewModel

public class MainWindowViewModel : INotifyPropertyChanged
{
    public BindingList<Connector> _connectors;

    public BindingList<Connector> CONNECTORS
    {
        get { return _connectors; }
        set
        {
            _connectors = value;
            OnPropertyChanged("");
        }
    }

    private MainWindowViewModel()
    {
        CONNECTORS = new BindingList<Connector>();
        CONNECTORS.RaiseListChangedEvents = true;
        CONNECTORS.AllowNew = true;
        CONNECTORS.AllowRemove = true;
        CONNECTORS.AllowEdit = true;

        CONNECTORS.Add(new Connector { ID = 1, X = 0, MoveX = 0 });

        CONNECTORS.AddingNew += (e, v) => AddConnector();
        CONNECTORS.ListChanged += (e, v) => UpdateConnectors();
    }

    void AddConnector()
    {
        Console.WriteLine("Added");
    }

    void UpdateConnectors()
    {
        Console.WriteLine("Updated");
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

XAML

<DataGrid Width="200" Margin="0 8 0 0" ItemsSource="{Binding CONNECTORS, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" CanUserSortColumns="True" CanUserDeleteRows="True" CanUserAddRows="True" AutoGenerateColumns="False" materialDesign:DataGridAssist.CellPadding="13 8 8 8" materialDesign:DataGridAssist.ColumnHeaderPadding="8">
                            <DataGrid.Columns>
                                <materialDesign:MaterialDataGridTextColumn Binding="{Binding ID}" Header="Id" IsReadOnly="True" EditingElementStyle="{StaticResource MaterialDesignDataGridTextColumnPopupEditingStyle}" />
                                <materialDesign:MaterialDataGridTextColumn Binding="{Binding X, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Header="X" EditingElementStyle="{StaticResource MaterialDesignDataGridTextColumnPopupEditingStyle}" />
                                <materialDesign:MaterialDataGridTextColumn Binding="{Binding MoveX, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Header="Move X" EditingElementStyle="{StaticResource MaterialDesignDataGridTextColumnPopupEditingStyle}" />
                            </DataGrid.Columns>
                        </DataGrid>

两个方法(AddConnector()UpdateConnectors())仅在添加新行时调用。

UpdateConnectors()应该在每次更改时都打开

0 个答案:

没有答案