【发布时间】:2018-08-03 23:16:58
【问题描述】:
我试图在DataGrid 中反映ObservableCollection 的变化。
我的问题是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}"/>
【问题讨论】:
-
那么问题出在哪里?请详细说明您看到的结果、任何错误等。(我假设您过早地切断了 DataGrid 的 XAML,因为您至少缺少一些结束标记。)
-
我的问题是当我在集合中添加新元素时 DataGrid 不显示更改 DataGrid 中没有新行。
-
这听起来可能很愚蠢,但是您是否将视图模型设置为数据上下文?我看到的只是一个视图模型和一个控件,但不知道你是否将它们相互连接起来。
-
我没有看到显示的代码或 XAML 有任何问题。因此,我做了一个测试项目。我无法复制这个问题。您提供的代码未显示您如何添加新的配置实例。请添加,以便我看一下。
-
要补充 Jeff 所说的,如果您没有将视图模型设置为 DataContext,您应该会在“输出”窗口中看到数据绑定错误。
标签: c# wpf binding observablecollection