Avalonia错误AVLN:0004:如何在PostRow控件中访问Test命令
解决Avalonia PostRow控件访问父级ViewModel命令的问题
你遇到的错误是因为PostRow的DataContext绑定的是Post模型对象,而Test命令并不定义在这个模型里,所以绑定无法解析。下面提供两种实用的解决方法:
方法1:通过RelativeSource绑定到父级ViewModel
直接在PostRow的按钮绑定中,通过RelativeSource向上查找包含目标命令的父级DataContext(比如承载ItemsControl的页面ViewModel):
<!-- PostRow.axaml 中的按钮绑定 --> <Button Command="{Binding DataContext.Test, RelativeSource={RelativeSource AncestorType=ItemsControl}}" />
- 原理:
RelativeSource={RelativeSource AncestorType=ItemsControl}会找到当前PostRow所在的ItemsControl,而ItemsControl的DataContext是你的页面ViewModel(包含Test命令),所以通过DataContext.Test就能拿到目标命令。 - 如果ItemsControl的父容器(比如UserControl/Window)的DataContext才是ViewModel,把
AncestorType换成对应的容器类型即可。
方法2:给PostRow添加命令依赖属性
这种方式更适合控件复用,把命令作为PostRow的属性从外部传入:
- 在
PostRow.axaml.cs中定义依赖属性:
public class PostRow : UserControl { public static readonly StyledProperty<ICommand> TestCommandProperty = AvaloniaProperty.Register<PostRow, ICommand>(nameof(TestCommand)); public ICommand TestCommand { get => GetValue(TestCommandProperty); set => SetValue(TestCommandProperty, value); } // 其他构造函数等代码 }
- 在Posts.axaml中使用PostRow时,绑定这个属性:
<ItemsControl ItemsSource="{Binding Posts}"> <ItemsControl.ItemTemplate> <DataTemplate> <local:PostRow TestCommand="{Binding DataContext.Test, RelativeSource={RelativeSource AncestorType=ItemsControl}}" /> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl>
- 在PostRow.axaml中绑定自身的TestCommand属性:
<Button Command="{Binding TestCommand, RelativeSource={RelativeSource Self}}" />
(或者如果PostRow的DataContext没被覆盖,也可以直接{Binding TestCommand},但用RelativeSource Self更稳妥)
内容的提问来源于stack exchange,提问作者Kyle Corbin Hurst
相关产品推荐
相关产品推荐

