简体   繁体   English

Datagrid到ObservableCollection绑定不更新网格

[英]Datagrid to ObservableCollection Binding Doesn't Update grid

Please help me, I have no idea whats wrong. 请帮帮我,我不知道什么是错的。 No matter what I try, the grid is just not updated (stays empty). 无论我尝试什么,网格都不会更新(保持空白)。

I want the grid to be bound to an ObservableCollection, but not to genrate automatic cloumns, but to choose two Properties from the object called Product, which is the type this Collection holds. 我希望网格绑定到ObservableCollection,但不要生成自动cloumns,而是从名为Product的对象中选择两个属性,这是此Collection所拥有的类型。

XAML: XAML:

 <DataGrid  x:Name="itemsGrid" ItemsSource="{Binding OrdersList}" AutoGenerateColumns="False" Style="{StaticResource GridStyle}">
     <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Path=Product.Amount}" Header="AMOUTN" />
        <DataGridTextColumn Binding="{Binding Path=Product.Name}" Header="NAME"  />
     </DataGrid.Columns>
</DataGrid >

CODE: 码:

  public partial class Orders : Window,INotifyPropertyChanged
    {

      ObservableCollection<Product> _ordersList = new ObservableCollection<Product>();
      public event PropertyChangedEventHandler PropertyChanged;

      private ObservableCollection<Product> OrdersList
    {
        get { return this._ordersList; }

        set { _ordersList = value; NotifyPropertyChanged("OrdersList"); }
    }

    private void addProduct(Product p)
    {
        OrdersList.Add(p);
        NotifyPropertyChanged("OrdersList");
    }
    private void removeProduct(Product p)
    {
        OrdersList.Remove(p);
        NotifyPropertyChanged("OrdersList");
    }

    protected void NotifyPropertyChanged(String propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

} }

I think you simply need to remove the word Product. 我想你只需要删除Product.一词Product. from your bindings. 来自你的绑定。 The DataContext of each DataGridRow is an object of type Product , so your binding should point to the properties on Product 每个DataGridRowDataContext都是Product类型的对象,因此您的绑定应指向Product上的属性

 <DataGrid.Columns>
    <DataGridTextColumn Binding="{Binding Path=Amount}" Header="AMOUNT" />
    <DataGridTextColumn Binding="{Binding Path=Name}" Header="NAME"  />
 </DataGrid.Columns>

You need to set this.DataContext = this; 你需要设置this.DataContext = this; somewhere. 某处。 This is best done in the window's Load event. 这最好在窗口的Load事件中完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM