如何从ItemTemplate UWP中的DataContext获取命令

时间:2018-05-02 12:49:53

标签: uwp uwp-xaml

我有XAML代码的下一部分

<ListView x:Name="FavoritesList" Grid.Row="0" Grid.ColumnSpan="3" Grid.RowSpan="1" Grid.Column="0" HorizontalContentAlignment="Stretch" HorizontalAlignment="Stretch" VerticalAlignment="Top" ItemsSource="{Binding Favorites.FavoritesVideos, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" >
        <ListView.ItemTemplate>
            <DataTemplate x:DataType="local:FavoriteItem">
                <StackPanel Margin="10" Orientation="Horizontal">
                    <Button Content="&#59240;" Command="{Binding ElementName=listBox, Path=DataContext.ToPlayer}" CommandParameter="{Binding ElementName=Source, Path=Text}" FontFamily="Segoe MDL2 Assets" Background="Transparent" HorizontalAlignment="Right"/>
                    <TextBlock x:Name="Source" FontSize="18" Text="{Binding Path}" HorizontalAlignment="Right" VerticalAlignment="Center"/>
                    <TextBlock FontSize="23" Text="{Binding Name}" Foreground="#FFFF2F00" HorizontalAlignment="Right" VerticalAlignment="Center"/>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

如您所见,我需要将命令绑定到DataContextItemTemplate内的按钮,但我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

我解决了一个问题。

<ListView x:Name="FavoritesList" Grid.Row="0" Grid.ColumnSpan="3" Grid.RowSpan="1" Grid.Column="0" HorizontalContentAlignment="Stretch" HorizontalAlignment="Stretch" VerticalAlignment="Top" ItemsSource="{Binding Favorites.FavoritesVideos, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" >
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="local:FavoriteItem">
            <StackPanel Margin="10" Orientation="Horizontal">
                <Button Content="&#59240;" Command="{Binding ElementName=***FavoritesList***, Path=DataContext.ToPlayer}" CommandParameter="{Binding ElementName=Source, Path=Text}" FontFamily="Segoe MDL2 Assets" Background="Transparent" HorizontalAlignment="Right"/>
                <TextBlock x:Name="Source" FontSize="18" Text="{Binding Path}" HorizontalAlignment="Right" VerticalAlignment="Center"/>
                <TextBlock FontSize="23" Text="{Binding Name}" Foreground="#FFFF2F00" HorizontalAlignment="Right" VerticalAlignment="Center"/>
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>