我正在尝试反映ObservableCollection
中DataGrid
的变化。
我的问题是,当我在集合中添加新元素时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}"/>
答案 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}"/>