将ObservableCollection绑定到DataGrid

时间:2016-07-25 13:02:06

标签: wpf .net-4.5

如何将ObservableCollection<updateData> updateCollection绑定到DataGrid?我尝试了几个解决方案,但似乎没有工作,因为行已添加到集合中但不会显示在网格上。我试图只绑定到类,然后我可以添加行,但是当我尝试编辑它时,我得到错误'EditItem' is not allowed for this view。网格如下

<DataGrid Name="dgv" Grid.ColumnSpan="7"  AutoGenerateColumns="False" ItemsSource="{Binding updateCollection}" IsSynchronizedWithCurrentItem="True" CanUserAddRows="False">
<DataGrid.Columns>
    <DataGridComboBoxColumn Header="Hour" SelectedValueBinding="{Binding Active}" ItemsSource="{StaticResource hoursList}" DisplayMemberPath="Key" SelectedValuePath="Value"/>
    <DataGridComboBoxColumn Header="Origin" SelectedValueBinding="{Binding Origin}" ItemsSource="{StaticResource originList}" DisplayMemberPath="Key" SelectedValuePath="Value"/>
    <DataGridTextColumn Header="P" Binding="{Binding Path=Price}"/>
    <DataGridTextColumn Header="Q" Binding="{Binding Path=Quantity}"/>
</DataGrid.Columns>

updateData类如下:

public class updateData
{
    public string Price { get; set; }
    public string Quantity { get; set; }
    public string Origin { get; set; }
    public string Hour { get; set; }
}

1 个答案:

答案 0 :(得分:4)

你所做的看起来是正确的,但如果你错过了一件事,DataContext ......什么都行不通。 这里有一个适合你的例子:

这是你的模特:

public class updateData
{
    public string Price { get; set; }
    public string Quantity { get; set; }
    public string Origin { get; set; }
    public string Hour { get; set; }
}

请注意,如果您想告诉您的观点某些内容已发生变化,您必须实施INotifyPropertyChanged界面。

这是您的ViewModel:

public class updateDataVm
{
    public ObservableCollection<updateData> updateCollection { get; set; }

    public updateDataVm()
    {
        updateCollection = new ObservableCollection<updateData>(); 
    }
}

最后,这是您的观点(请注意,我已将ItemsSource更改为ItemsSource="{Binding}"):

<Grid>
    <DataGrid Name="dgv" Grid.ColumnSpan="7"  AutoGenerateColumns="False" ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True" CanUserAddRows="False">
    <DataGrid.Columns>
        <DataGridComboBoxColumn Header="Hour" SelectedValueBinding="{Binding Active}" ItemsSource="{StaticResource hoursList}" DisplayMemberPath="Key" SelectedValuePath="Value"/>
        <DataGridComboBoxColumn Header="Origin" SelectedValueBinding="{Binding Origin}" ItemsSource="{StaticResource originList}" DisplayMemberPath="Key" SelectedValuePath="Value"/>
        <DataGridTextColumn Header="P" Binding="{Binding Path=Price}"/>
        <DataGridTextColumn Header="Q" Binding="{Binding Path=Quantity}"/>
    </DataGrid.Columns>
</DataGrid>
</Grid>

在你的窗口(或一般控制):

public partial class MainWindow : Window
{
    public updateDataVm collection;
    public MainWindow()
    {
        InitializeComponent();

        collection = new updateDataVm();
        DataContext = collection;
    }
}