如何将命令绑定到它的" TemplatedParent"

时间:2016-02-01 11:28:53

标签: c# wpf xaml data-binding

如何绑定按钮的命令" myCmdButton"到ParameterVariableList,就像" addBtn"做。 " addBtn"工作得像预期。 我也想要另一个按钮命令到我的ParameterVariableList类。

这是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:找不到用于绑定的源代码&#39; RelativeSource FindAncestor,AncestorType =&#39; hmi.ParameterVariableList&#39;,AncestorLevel =&#39; 1&#39;&#39; 。 BindingExpression:路径= RemoveEntryCmd;的DataItem = NULL;目标元素是&#39;按钮&#39; (名称=&#39;&#39);目标财产是&#39; Command&#39; (键入&#39; ICommand&#39;)

2 个答案:

答案 0 :(得分:0)

这应该有效

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

答案 1 :(得分:0)

这有效:

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

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