WPF ObservableCollection更新DataGrid MVVM

时间:2018-08-03 23:16:58

标签: c# wpf binding observablecollection

我正在尝试反映ObservableCollectionDataGrid的变化。 我的问题是,当我在集合中添加新元素时DataGrid不显示更改,DataGrid中没有新行。 这是绑定到Window的ViewModel

 public class MainWindowViewModel : INotifyPropertyChanged
{
    private ObservableCollection<Configuration> configuration;
    public MainWindowViewModel()
    {
        configuration = new ObservableCollection<Model.Configuration>();
    } 
public ObservableCollection<Configuration> Configuration { 
                get { return configuration; } 
                set { configuration = value; 
                      OnProperyChanged("Configuration"); 
                 }}
 #region INotifyPropertyChanged Members
    public event PropertyChangedEventHandler PropertyChanged;

    private void OnProperyChanged(string propertyChanged)
    {
        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyChanged));
        }
    }
    #endregion}

我的DataGrid

<DataGrid x:Name="maintable" IsReadOnly="True" ItemsSource="{Binding Configuration}" CanUserAddRows="False" AutoGenerateColumns="False" Height="180" Margin="10,61,391,0" VerticalAlignment="Top">
                    <DataGrid.Columns>
                        <DataGridTextColumn Header="ID" Binding="{Binding Id}"/>
                        <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                        <DataGridTextColumn Header="Price" Binding="{Binding Price}"/>
                        <DataGridTextColumn Header="Description" Width="300"  Binding="{Binding Description}"/>

1 个答案:

答案 0 :(得分:0)

由于DataGrid ItemsSource中的某种原因,需要添加Mode=OneWay,现在,当更改ObservableCollection时,DataGrid正在更新

<DataGrid x:Name="maintable" IsReadOnly="True" ItemsSource="{Binding Configuration, Mode=OneWay}" CanUserAddRows="False" AutoGenerateColumns="False" Height="180" Margin="10,61,391,0" VerticalAlignment="Top">
                    <DataGrid.Columns>
                        <DataGridTextColumn Header="ID" Binding="{Binding Id}"/>
                        <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                        <DataGridTextColumn Header="Price" Binding="{Binding Price}"/>
                        <DataGridTextColumn Header="Description" Width="300"  Binding="{Binding Description}"/>