我用MVVM模式制作了UWP应用(我认为是:))
我的应用程序具有用于列表框的数据模板。
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中为绑定(bind)到DownloadCommand的按钮设置了什么?
最佳答案
尝试使用:
<Button Command="{Binding Path=DataContext.DownloadCommand, ElementName=lbMySongs}"
CommandParameter="{Binding}"
Content="{Binding Path=Query}"/>
并改变
public RelayCommand DownloadCommand { get; set; }
到
public RelayCommand<SomeClass> DownloadCommand { get; set; }
...
DownloadCommand = new RelayCommand<SomeClass>(DownloadExecute);
...
private voir DownloadExecute(SomeClass item)
{
...
}
关于c# - DataTemplate中的绑定(bind)命令,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39642758/