UNO .NET 5.0下ObservableCollection无法绑定UserControl中DataGrid问题求助
解决方案
Uno平台对WPF风格的RelativeSource Mode=FindAncestor语法兼容性有限,不需要使用该写法即可实现需求,以下是两种可行的落地方式:
方案1 最简修改(无需调整后台代码)
你已经在用户控件构造函数中手动将dgAuthors的DataContext设置为当前控件实例,因此不需要额外通过RelativeSource查找上级,直接修改XAML绑定语句即可:
<DataGrid Grid.Row="0" x:Name="dgAuthors" ItemsSource="{Binding Authors}" />
方案2 符合MVVM规范的ElementName绑定(无需后台硬编码设置DataContext)
首先删除构造函数中的dgAuthors.DataContext = this;代码,然后在用户控件的根节点设置x:Name,直接通过元素名绑定属性即可:
<!-- UserControl根节点设置名称 --> <UserControl x:Class="你的命名空间.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="SelfControl"> <Grid> <DataGrid Grid.Row="0" x:Name="dgAuthors" ItemsSource="{Binding Authors, ElementName=SelfControl}" /> </Grid> </UserControl>
两种方案都不需要修改你已经写好的Authors依赖属性代码,父页面传递集合到用户控件的写法保持不变:
<!-- 父页面使用自定义控件 --> <local:UserControl1 Authors="{Binding 父级ViewModel中的作者集合属性}" />
内容的提问来源于stack exchange,提问作者MATTA
相关产品推荐
相关产品推荐

