DataTemplate中的Binding命令

本文关键字:命令 Binding 中的 DataTemplate | 更新日期: 2023-09-27 18:08:31

我用MVVM模式制作了UWP应用程序(我认为是:))我的应用程序有数据模板的列表框。ListBox in View.xaml:

<ListBox x:Name="lbMySongs" ItemsSource="{Binding Path=MySongs}" ItemTemplate="{StaticResource lbSongsTemplate}" Grid.Row="1">
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
            </Style>
        </ListBox.ItemContainerStyle>
</ListBox/>

DateTemplate资源:

       <DataTemplate x:Key="lbSongsTemplate">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="auto"/>
                <ColumnDefinition Width="auto"/>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="auto"/>
                <ColumnDefinition Width="auto"/>
            </Grid.ColumnDefinitions>
            <TextBlock Text="{Binding Path=Artist}" Grid.Column="0"/>
            <TextBlock Text=" - " Grid.Column="1"/>
            <TextBlock Text="{Binding Path=Title}" Grid.Column="2"/>
            //Here i bind command, but it's not binding cos ItemsSource have no command. ViewModel have this command.
            <Button Command="{Binding Path=DownloadCommand}" Content="{Binding Path=Query}"/>
            <TextBlock Text="{Binding Duration}" Grid.Column="5" HorizontalAlignment="Right"/>
        </Grid>
       </DataTemplate>

需要为这个按钮设置DataContext。我在ViewModel中的命令。例子:

class ViewModel
{
    ...
    public RelayCommand DownloadCommand { get; set; }
    public ObservableCollection<SomeClass> MySongs { get; set; }
    ...
}

我的问题:DataTemplate有ItemsSource = ViewModel.MySongs。但DownloadCommand是在ViewModel中。我在DataTemplate中为我的按钮集绑定到DownloadCommand输入什么?

DataTemplate中的Binding命令

尝试使用:

<Button Command="{Binding Path=DataContext.DownloadCommand, ElementName=lbMySongs}"
        CommandParameter="{Binding}"
        Content="{Binding Path=Query}"/>

And change

public RelayCommand DownloadCommand { get; set; }

public RelayCommand<SomeClass> DownloadCommand { get; set; }
...
DownloadCommand = new RelayCommand<SomeClass>(DownloadExecute);
...
private voir DownloadExecute(SomeClass item)
{
    ...
}

使用RelativeSource绑定表示要绑定到ListBox.DataContext.DownloadCommand

<Button Command="{Binding Path=DataContext.DownloadCommand, 
                          RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}" 
        Content="{Binding Path=Query}"/>

通常的做法是将CommandParameter绑定到项目上,以知道命令在哪个项目上执行:

<Button Command="{Binding Path=DataContext.DownloadCommand, 
                          RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}" 
        CommandParameter="{Binding }"
        Content="{Binding Path=Query}" />

你也可以使用ElementName绑定,但是你必须给你的ListBox一个名字在你的DataTemplate中指定,我个人不喜欢在我的DataTemplate中硬编码ElementName。如果你改变了一些东西的名字,或者想要在另一个ListBox中使用DataTemplate,这使得查找和修复变得很烦人。