C# WPF ObservableCollection更新数据网格MVVM
我试图反映C# WPF ObservableCollection更新数据网格MVVM,c#,wpf,binding,observablecollection,C#,Wpf,Binding,Observablecollection,我试图反映数据网格中的可观察收集更改。 我的问题是,DataGrid在集合中添加新元素时不显示更改,DataGrid中没有新行。 这是绑定到窗口的ViewModel类 public class MainWindowViewModel : INotifyPropertyChanged { private ObservableCollection<Configuration> configuration; public MainWindowViewModel()
数据网格
中的可观察收集
更改。
我的问题是,DataGrid
在集合中添加新元素时不显示更改,DataGrid
中没有新行。
这是绑定到窗口的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
ItemsSource
中的某些原因,需要添加Mode=OneWay
,现在DataGrid在ObservableCollection更改时更新
<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}"/>
那么问题出在哪里?请详细说明您看到的结果、任何错误等(我假设您过早地切断了DataGrid的XAML,因为您至少丢失了一些结束标记。)我的问题是DataGrid在集合中添加新元素时不会显示更改DataGrid中没有新行。这听起来可能很愚蠢,但是您是否将视图模型设置为数据上下文?我看到的只是一个视图模型和一个控件,但我不知道它们是否相互连接。我没有看到显示的代码或XAML有任何错误。因此,我做了一个测试项目。我不能重复这个问题。您提供的代码没有显示如何添加新的配置实例。请添加它,以便我可以查看一下。要添加Jeff所说的内容,如果您没有将视图模型设置为DataContext,您应该会在输出窗口中看到数据绑定错误。我很高兴它对您有效,但还有其他方面在起作用。首先,绑定方向只影响配置属性,而不影响其项。这已经设定好了,但没有改变。第二,我使用的是默认模式,它是双向的,我的示例运行得很好。
<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}"/>