如何将命令绑定到其“模板父”

本文关键字:模板父 命令 绑定 | 更新日期: 2023-09-27 18:32:40

如何将按钮"myCmdButton"的命令绑定到ParameterVariableList,就像"addBtn"一样。"addBtn"的工作方式与预期相同。我也想要另一个按钮命令到我的参数变量列表类。

下面是 XAML:

<DataTemplate DataType="{x:Type locale:ParameterVariableList}" >
    <StackPanel Orientation="Vertical">
        <TextBlock Text="{Binding Description}"/>
        <Button Content="add" Command="{Binding AddEntryCmd}" Name="addBtn" />
        <ListBox ItemsSource="{Binding ItemList, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Stretch" >
            <ListBox.ItemTemplate>
                <ItemContainerTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding}" />
                        <Button Width="{Binding ActualHeight, RelativeSource={RelativeSource Self}}" Command="{Binding RemoveEntryCmd, ???}" Name="myCmdButton" >
                            <Image Source="Resources/trash_16x16.png" Stretch="None" VerticalAlignment="Center" HorizontalAlignment="Center" />
                        </Button>
                    </StackPanel>
                </ItemContainerTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </StackPanel>
</DataTemplate>

我期望这能工作,但它没有:

Command="{Binding RemoveEntryCmd, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type locale:ParameterVariableList}}}"

错误:System.Windows.Data 错误: 4 : 找不到引用 'RelativeSource FindAncestor, AncestorType='hmi 进行绑定的源。ParameterVariableList', AncestorLevel='1'''.BindingExpression:Path=RemoveEntryCmd;数据项=空;目标元素是"按钮"(名称=");目标属性为"命令"(类型为"ICommand")

如何将命令绑定到其“模板父”

这有效:

Command="{Binding DataContext.RemoveEntryCmd, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}"

几乎是Abhinav的答案,但DataContext缺失。

这应该有效

Command="{Binding RemoveEntryCmd,RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type ListBox}}}