Я сделал приложение UWP с шаблоном MVVM (я так думаю :)) У моего приложения есть шаблон данных для списка. ListBox в View.xaml:Команда привязки в DataTemplate
<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?
Выберите кнопку -> Нажмите «F4» на клавиатуре, вы увидите свойства -> выполнить команду -> Нажмите кнопку «Маленький серый» после текстового поля, выберите «Создать привязку» -> из окна привязки, выберите «DownloadCommand» - > Voila – AVK