无法将 ObservableCollection 绑定到 UserControl 中的 DataGrid

Unable to bind ObservableCollection to DataGrid in UserControl

我正在尝试将 ObservableCollection 从 XAML 页面传递到 UserControl。

在正常的 Visual Studio WPF 项目 .NET Framework 4.8 中,在 UserControl 中,下面的 XAML 代码工作正常并且可以在页面中看到数据。

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

用户控件隐藏代码如下:

    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);

但是在UNO for .NET 5.0 framework中,当在DataGrid的ItemSource中使用Binding时,无法找到Mode=FindAncestorAncestorType

非常感谢任何帮助。

非常感谢

尼拉吉

使用 Uno Platform 使用的 XAML 的 WinUI 风格,您可以使用 x:Bind syntax 绑定到代码隐藏中的 属性:

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