除非刷新,否则ObservableCollection会添加未在datagrid上显示的新项目

时间:2018-04-23 15:09:48

标签: c# wpf datagrid observablecollection

我有一个ObservableCollection列表,并设置绑定到WPF中的数据网格。但是,当我向列表中添加项时,除非我刷新itemssource,否则datagrid不会更新。

这是我的代码。

ObservableCollection<FLEET_SERIES> listAC = new ObservableCollection<FLEET_SERIES>();
///Add some items to listAC

这是我在列表中添加其他项目的地方

private void AcTypeDtg_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{

    listAC.Add(new FLEET_SERIES()
    {
        PART_NUMBER= "SOMESTRING"
        FLEET = null,
        SERIES=null        
    });
}

这是我的datagrid的xaml代码

<DataGrid 
    Name="AcTypeDtg" 
    IsSynchronizedWithCurrentItem="True" 
    ItemsSource="{Binding listAC, UpdateSourceTrigger=PropertyChanged, NotifyOnSourceUpdated=True,NotifyOnTargetUpdated=True}"  
    CanUserAddRows="False" 
    AutoGenerateColumns="False" 
    PreviewMouseRightButtonDown="AcTypeDtg_MouseRightButtonDown"
    >
    <DataGrid.Columns>
        <DataGridTextColumn 
            x:Name="fleetCol" 
            Header="Fleet" 
            Width = "100*" 
            IsReadOnly="True" 
            Binding="{Binding FLEET, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged,NotifyOnSourceUpdated=True,NotifyOnTargetUpdated=True}"
            >
        </DataGridTextColumn>

        <DataGridTextColumn 
            Header="Series" 
            x:Name="SeriesColumn" 
            Width = "100*" 
            IsReadOnly="True" 
            Binding="{Binding SERIES, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged,NotifyOnSourceUpdated=True,NotifyOnTargetUpdated=True}"
            >
        </DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

这是我的班级FLEET_SERIES

public partial class FLEET_SERIES:INotifyPropertyChanged
{

    #region Members
    private string _pART_NUMBER;
    private string _fLEET;
    private string _sERIES;
    #endregion

    #region Properties
    public string PART_NUMBER { get { return _pART_NUMBER; } set { _pART_NUMBER = value; OnPropertyChanged("PART_NUMBER"); } }
    public string FLEET { get { return _fLEET; } set { _fLEET = value; OnPropertyChanged("FLEET"); } }
    public string SERIES { get { return _sERIES; } set { _sERIES = value; OnPropertyChanged("SERIES"); } }
    #endregion

    // INotifyPropertyChanged interface       
    public event PropertyChangedEventHandler PropertyChanged;

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

所以当我添加一个额外的项目。 datagrid不会更新。但是,如果我将itemssource设置为null,然后设置为listAC。它会显示添加的附加项目。知道为什么吗?

我认为ObservableCollection已经实现了collectionchange。我需要一个单独的处理程序来处理collectionchange吗?....谢谢你的帮助。

0 个答案:

没有答案