Home Forums WPF controls Xceed DataGrid for WPF Example using ObservableCollection

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • User (Old forums)
    Member
    Post count: 23064
    #27210 |

    I am currently looking at using the Xceed WPF DataGrid. I am looking at the sample (from C:\Xceed Samples\Xceed DataGrid for WPF v2.0\CSharp\DataBinding) to get my head around it. In particular I need to get it working with ObservableCollection.

    I have attempted to change the sample to use an ObservableCollection rather than a Datatable. As such I have been playing around with the BindToDataGridCollectionView method in the sample.

    I can do binding fine (source code is below the exception) but if I click on the ‘new record’ line in the grid I get the below exception occurring (note I am unable to trap the exception).

    Any suggestions as to how to get the sample working with ObservableCollection? Or maybe someone could point me to a similar working example elsewhere? If you have it locally it would be great if you could zip it up and upload it somewhere (such as http://www.mediafire.com).

    Note I have also attempted to download the file mentioned right at the end of http://xceed.com/CS/forums/thread/7054.aspx but it is 404ing.

    Exception

    System.InvalidOperationException was unhandled
      Message=”An attempt was made to add a new data item to a source that does not support insertion.”
      Source=”Xceed.Wpf.DataGrid”
      StackTrace:
           at Xceed.Wpf.DataGrid.ItemsSourceHelper.AddNewDataItem(DataGridContext dataGridContext, Int32& itemIndex)
           at Xceed.Wpf.DataGrid.InsertionRow.AddNewItemAndInitCells(DataGridContext dataGridContext, Boolean cellAlreadyHasValue)
           at Xceed.Wpf.DataGrid.InsertionRow.BeginEdit()
           at Xceed.Wpf.DataGrid.Row.OnCellIsBeingEdited_ClassHandler(Object sender, RoutedEventArgs e)
           at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
           at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
           at System.Windows.UIElement.RaiseEventImpl(RoutedEventArgs args)
           at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
           at Xceed.Wpf.DataGrid.Cell.OnIsBeingEditedChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
           at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
           at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
           at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
           at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, OperationType operationType)
           at System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, OperationType operationType, Boolean isInternal)
           at System.Windows.DependencyObject.SetValue(DependencyPropertyKey key, Object value)
           at Xceed.Wpf.DataGrid.Cell.SetIsBeingEdited(Boolean value)
           at Xceed.Wpf.DataGrid.Cell.BeginEdit()
           at Xceed.Wpf.DataGrid.Cell.OnPreviewGotKeyboardFocus(KeyboardFocusChangedEventArgs e)
           at System.Windows.UIElement.OnPreviewGotKeyboardFocusThunk(Object sender, KeyboardFocusChangedEventArgs e)
           at System.Windows.Input.KeyboardFocusChangedEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
           at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
           at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
           at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
           at System.Windows.UIElement.RaiseEventImpl(RoutedEventArgs args)
           at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
           at System.Windows.Input.InputManager.ProcessStagingArea()
           at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
           at System.Windows.Input.KeyboardDevice.TryChangeFocus(DependencyObject newFocus, IKeyboardInputProvider keyboardInputProvider, Boolean askOld, Boolean askNew, Boolean forceToNullIfFailed)
           at System.Windows.Input.KeyboardDevice.Focus(DependencyObject focus, Boolean askOld, Boolean askNew)
           at System.Windows.Input.KeyboardDevice.Focus(IInputElement element)
           at System.Windows.UIElement.Focus()
           at Xceed.Wpf.Controls.AutoSelectTextBox.OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
           at System.Windows.UIElement.OnPreviewMouseLeftButtonDownThunk(Object sender, MouseButtonEventArgs e)
           at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
           at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
           at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
           at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
           at System.Windows.UIElement.ReRaiseEventAs(RoutedEventArgs args, RoutedEvent newEvent)
           at System.Windows.UIElement.OnPreviewMouseDownThunk(Object sender, MouseButtonEventArgs e)
           at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
           at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
           at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
           at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
           at System.Windows.UIElement.RaiseEventImpl(RoutedEventArgs args)
           at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
           at System.Windows.Input.InputManager.ProcessStagingArea()
           at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
           at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
           at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
           at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
           at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
           at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
           at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
           at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
           at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
           at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
           at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
           at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
           at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
           at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
           at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
           at System.Windows.Threading.Dispatcher.Run()
           at System.Windows.Application.RunInternal(Window window)
           at System.Windows.Application.Run(Window window)
           at System.Windows.Application.Run()
           at Xceed.Wpf.DataGrid.Samples.DataBinding.App.Main() in C:\Xceed Samples\Xceed DataGrid for WPF v2.0\CSharp\DataBinding\obj\Debug\App.g.cs:line 0
           at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
           at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
           at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
           at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart()

    Source Code

    New code:

     

    using System;

    using

    System.Collections.Generic;

    using

    System.Text;

    using

    System.Windows;

    using

    System.ComponentModel;

    namespace

    Xceed.Wpf.DataGrid.Samples.DataBinding

    {

    public class Product : DependencyObject, INotifyPropertyChanged

    {

    public static readonly DependencyProperty CategoryProperty = DependencyProperty.Register(“Category”, typeof(string), typeof(Product));

    public static readonly DependencyProperty ProductNameProperty = DependencyProperty.Register(“ProductName”, typeof(string), typeof(Product));

    public static readonly DependencyProperty SupplierProperty = DependencyProperty.Register(“Supplier”, typeof(string), typeof(Product));

    public static readonly DependencyProperty UnitPriceProperty = DependencyProperty.Register(“UnitPrice”, typeof(decimal), typeof(Product));

    public static readonly DependencyProperty UnitsOnOrderProperty = DependencyProperty.Register(“UnitsOnOrder”, typeof(decimal), typeof(Product));

    public static readonly DependencyProperty DiscontinuedProperty = DependencyProperty.Register(“Discontinued”, typeof(bool), typeof(Product));

    public string Category

    {

    get { return (string)GetValue(CategoryProperty); }

    set { SetValue(CategoryProperty, value); }

    }

    public string ProductName

    {

    get { return (string)GetValue(ProductNameProperty); }

    set { SetValue(ProductNameProperty, value); }

    }

    public string Supplier

    {

    get { return (string)GetValue(SupplierProperty); }

    set { SetValue(SupplierProperty, value); }

    }

    public decimal UnitPrice

    {

    get { return (decimal)GetValue(UnitPriceProperty); }

    set { SetValue(UnitPriceProperty, value); }

    }

    public decimal UnitsOnOrder

    {

    get { return (decimal)GetValue(UnitsOnOrderProperty); }

    set { SetValue(UnitsOnOrderProperty, value); }

    }

    public bool Discontinued

    {

    get { return (bool)GetValue(DiscontinuedProperty); }

    set { SetValue(DiscontinuedProperty, value); }

    }

    #region

    INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)

    {

    base.OnPropertyChanged(e);

    if (PropertyChanged != null)

    PropertyChanged(

    this, new PropertyChangedEventArgs(e.Property.Name));

    }

     

    #endregion

    }

    }

    New method in App.xaml.cs:

    public ObservableCollection<Product> NewProducts

    {

    get

    {

    ObservableCollection<Product> col = new ObservableCollection<Product>();

    Product x = new Product();

    x.Category =

    “Cat1”;

    x.ProductName =

    “Prod1”;

    x.Supplier =

    “Supplier1”;

    x.UnitPrice = 1;

    x.UnitsOnOrder = 5;

    x.Discontinued =

    true;

    col.Add (x);

    x =

    new Product();

    x.Category =

    “Cat2”;

    x.ProductName =

    “Prod2”;

    x.Supplier =

    “Supplier2”;

    x.UnitPrice = 2;

    x.UnitsOnOrder = 10;

    x.Discontinued =

    false;

    col.Add (x);

    return col;

    }

    }

    Changed method in MainPage.xaml.cs:

    private void BindToDataGridCollectionView()

    {

    // With this binding, Adding, removing, and modifying data will work.

    txtDescription.Text =

    Data.DataGridCollectionViewText;

    // Reset the grid to its initial state.

    this.ResetGrid( true, true );

    // Create an Xceed DataGridCollectionView using the Products DataTable as its source.

    //DataGridCollectionView dataGridCollectionView = new DataGridCollectionView( ( ( App )Application.Current ).Products.DefaultView );

    ObservableCollection<Product> x = ((App)Application.Current).NewProducts;

     

    DataGridCollectionView dataGridCollectionView = new DataGridCollectionView(x);

    dataGridCollectionView.ItemProperties.Clear();

    dataGridCollectionView.ItemProperties.Add(

    new DataGridItemProperty(“Category”, “Category”, typeof(string)));

    dataGridCollectionView.ItemProperties.Add(

    new DataGridItemProperty(“ProductName”, “ProductName”, typeof(string)));

    dataGridCollectionView.ItemProperties.Add(

    new DataGridItemProperty(“Supplier”, “Supplier”, typeof(string)));

     

    dataGridCollectionView.ItemProperties.Add(

    new DataGridItemProperty(“UnitPrice”, “UnitPrice”, typeof(decimal)));

    dataGridCollectionView.ItemProperties.Add(

    new DataGridItemProperty(“UnitsOnOrder”, “UnitsOnOrder”, typeof(decimal)));

    dataGridCollectionView.ItemProperties.Add(

    new DataGridItemProperty(“Discontinued”, “Discontinued”, typeof(bool)));

    // Bind the grid to the Xceed DataGridCollectionView.

    grid.ItemsSource = dataGridCollectionView;

    // Hide unwanted columns.

    //grid.Columns[ “ProductID” ].Visible = false;

    //grid.Columns[ “ReorderLevel” ].Visible = false;

    //grid.Columns[ “UnitsInStock” ].Visible = false;

    //grid.Columns[ “QuantityPerUnit” ].Visible = false;

    // Configure comboBoxes.

    grid.Columns[

    “Supplier” ].Title = “Supplier”;

    grid.Columns[

    “Supplier” ].Width = 200;

    //grid.Columns[ “SupplierID” ].CellEditor = this.FindResource( “supplierEditor” ) as CellEditor;

    //grid.Columns[ “SupplierID” ].CellContentTemplate = this.FindResource( “supplierCellDataTemplate” ) as DataTemplate;

    grid.Columns[

    “Category” ].Title = “Category”;

    //grid.Columns[ “CategoryID” ].CellEditor = this.FindResource( “categoryEditor” ) as CellEditor;

    //grid.Columns[ “CategoryID” ].CellContentTemplate = this.FindResource( “categoryCellDataTemplate” ) as DataTemplate;

    grid.Columns[

    “Discontinued” ].VisiblePosition = grid.Columns.Count;

    grid.Columns[

    “ProductName” ].Width = 200;

    }

     

    Imported from legacy forums. Posted by Matthew (had 1870 views)

    User (Old forums)
    Member
    Post count: 23064

    Hi Matthew,

    In order to use the [Add New] functionality, you have to make sure that the following requirements are covered:

    (taken from http://doc.xceedsoft.com/products/XceedWpfDataGrid/Providing_Data.html)

    Inserting Data

    The DataGridCollectionView supports insertion as long as the underlying DataGridCollectionView-wrapped collection implements the IBindingList interface and its AllowNew property returns true. In this case, the AddNew method can be used to add new data items to the underlying collection, while the EndNew and CancelNew methods can be used to commit the new item or cancel its addition.

    —————————————

    I believe the error you are seeing is probably because one of these requirements are not fulfiled. It is not indicative of a binding problem with ObservableCollections.

    Hope that helps in some way..!

    Cheerios,

    Serene
     

    Imported from legacy forums. Posted by Serene (had 2238 views)

    User (Old forums)
    Member
    Post count: 23064

    I was experiencing the same issue.  I was able to work around it by implementing a Custom ObservableCollection<T> that implemented IBindingList or by using BindableCollection<T> instead of ObservableCollection.  I am still able to get property notfication changes via the BindableCollection.

    Imported from legacy forums. Posted by Rob (had 1446 views)

    User (Old forums)
    Member
    Post count: 23064

    [quote user=”Rob”]

    I was experiencing the same issue.  I was able to work around it by implementing a Custom ObservableCollection<T> that implemented IBindingList or by using BindableCollection<T> instead of ObservableCollection.  I am still able to get property notfication changes via the BindableCollection.

    [/quote]

     

    Would you be able to email me your custom ObservableCollection code? I have had a bash but am not getting anywhere…

     

    I have private messaged you with my email address…

    Imported from legacy forums. Posted by Matthew (had 2660 views)

Viewing 4 posts - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.