Telerik WPF RadGridView DataTemplate按钮命令绑定失败求助
问题根源
你用RelativeSource FindAncestor查找PlannerOverviewViewModel类型是错误的——FindAncestor只能遍历可视化树中的UI元素,而ViewModel是数据模型,不属于可视化树节点,因此绑定无法找到目标命令。
可行解决方案
方案1:通过ElementName绑定RadGridView的DataContext
利用RadGridView的DataContext就是ViewModel的特性,直接通过控件名称绑定:
<telerik:RadButton x:Name="BtnDeleteOrganinsationUnit" Command="{Binding DataContext.DeleteOrganisationUnitCommand, ElementName=ViewResponsibleOrganisationUnits}" CommandParameter="{Binding}"> <StackPanel Orientation="Horizontal" Margin="0,0"> <mahapps:PackIconMaterial Kind="CloseBox" HorizontalAlignment="Center" VerticalAlignment="Center" Width="14" Height="14" Foreground="{StaticResource ArcelorAccentBrush}"/> </StackPanel> </telerik:RadButton>
ElementName=ViewResponsibleOrganisationUnits指向你的RadGridView控件CommandParameter="{Binding}"将当前行的组织单元数据传递给命令,确保ViewModel知道要删除哪一项
方案2:直接引用资源中的ViewModel
因为你已经在UserControl资源中定义了ViewModel实例,可以直接用StaticResource绑定:
<telerik:RadButton x:Name="BtnDeleteOrganinsationUnit" Command="{Binding DeleteOrganisationUnitCommand, Source={StaticResource ViewModel}}" CommandParameter="{Binding}"> <!-- 按钮内容不变 --> </telerik:RadButton>
方案3:通过UserControl的DataContext绑定(若已设置)
如果你的UserControl已经将DataContext设置为该ViewModel(比如<UserControl DataContext="{StaticResource ViewModel}"/>),可以查找父级UserControl的DataContext:
<telerik:RadButton x:Name="BtnDeleteOrganinsationUnit" Command="{Binding DataContext.DeleteOrganisationUnitCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" CommandParameter="{Binding}"> <!-- 按钮内容不变 --> </telerik:RadButton>
额外检查项
- 确保ViewModel中的
CanExecuteDeleteOrganisationUnitCommand方法返回true,否则按钮会处于禁用状态 - 验证
deleteOrganisationUnitCommand字段已正确初始化,避免空引用 - 命令执行方法
ExecuteDeleteOrganisationUnitCommandAsync中需正确处理传入的参数(即要删除的组织单元)
内容的提问来源于stack exchange,提问作者LudwigGhislain
相关产品推荐
相关产品推荐

