如何将ListItem绑定到CommandParameter

时间:2017-11-08 12:56:23

标签: c# wpf viewmodel

我有ListBox

<ListBox Margin="10" Padding="10" ItemsSource="{Binding Items}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <!-- Data template -->
            <Grid>
                <Grid.ColumnDefinitions>
                    <!--Image-->
                    <ColumnDefinition Width="auto" />
                    <!--Info-->
                    <ColumnDefinition Width="500" />
                    <!--Options-->
                    <ColumnDefinition Width="*" /
                </Grid.ColumnDefinitions>
                <Image Height="50" Width="50" />
                <StackPanel Grid.Column="1" HorizontalAlignment="Left">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="Name: " />
                        <TextBlock Text="{Binding Name}" />
                    </StackPanel>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="ID: " />
                        <TextBlock Text="{Binding ID}" />
                    </StackPanel>
                </StackPanel>
                <Button Grid.Column="2" Content="{Binding Status}" Command="{Binding CompleteCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MainPageViewModel}}}" CommandParameter="{Binding}" HorizontalAlignment="Right" />
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

我需要CommandParameter成为此ListItem的{​​{1}}。

1 个答案:

答案 0 :(得分:1)

AncestorType设置为ListBox并在路径中加入DataContext

<Button ... Command="{Binding DataContext.CompleteCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}" CommandParameter="{Binding}" HorizontalAlignment="Right"></Button>

如果Command属性属于与CompleteCommand属性相同的类

,则Items绑定应该有效