Search code examples
uno-platform

Unable to bind ObservableCollection to DataGrid in UserControl


I am trying to pass ObservableCollection from the XAML Page to the UserControl.

In a normal Visual Studio WPF project .NET Framework 4.8, within the UserControl the below XAML code works fine and the data can be seen within the Page.

<DataGrid Grid.Row="0" x:Name="dgAuthors" ItemsSource="{Binding Authors, RelativeSource= RelativeSource Mode=FindAncestor, AncestorType=local:UserControl1}}

Code behind of User Control as below:

    public UserControl1()
    {
        InitializeComponent();
        
        dgAuthors.DataContext = this;
    }

    public ObservableCollection<Author> Authors
    {
        get { return (ObservableCollection<Author>)GetValue(AuthorsProperty); }
        set { SetValue(AuthorsProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Authors.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty AuthorsProperty =
        DependencyProperty.Register("Authors", typeof(ObservableCollection<Author>), typeof(UserControl1), null);

But in UNO for .NET 5.0 framework, it is unable to find the Mode=FindAncestor and AncestorType when Binding is used within the ItemSource of the DataGrid.

Any help would be highly appreciated.

Many thanks

Neeraj


Solution

  • With the WinUI flavour of XAML used by Uno Platform, you can use x:Bind syntax to bind to a property in code-behind:

    <DataGrid Grid.Row="0" x:Name="dgAuthors" ItemsSource="{x:Bind Authors, Mode=OneWay}} />