我有一个 observableCollection,我在视图中使用 itemSource 循环。observablecollection 中的每个项目都包含一个按钮,该按钮将命令 (openSessionCommand) 发送到 viewModel。我的问题是 - 我怎样才能将 ID 发送回在 itemSource 中单击哪个按钮的 viewModel?
<ItemsControl ItemsSource="{Binding AvailableSessions}" Margin="490,181,10.111,39.111">
<ItemsControl.ItemTemplate>
<DataTemplate >
<Border BorderBrush="Black" Background="Gainsboro" BorderThickness="1" Margin="2">
<Grid Background="#FFECECEC">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Button Command="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type UserControl}}, Path=DataContext.OpenSessionCommand}"
HorizontalAlignment="Left" Margin="10,10,0,0"
VerticalAlignment="Top" Width="243" Height="42">
<TextBlock TextWrapping="Wrap">
<Run Text="{Binding SessionName}"/><LineBreak/>
<Run Text="{Binding Genre}"/><Run Text=" - "/><Run Text="{Binding Tempo}"/>
</TextBlock>
</Button>
<Label Content="{Binding AdminUsername}" HorizontalAlignment="Left"
Margin="10,53,0,0" VerticalAlignment="Top" Width="243" Height="26"/>
<Label Content="{Binding Client1Username}" HorizontalAlignment="Left"
Margin="10,71,0,0" VerticalAlignment="Top" Width="243" Height="25"/>
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.Template>
<ControlTemplate TargetType="ItemsControl">
<ScrollViewer CanContentScroll="True">
<ItemsPresenter/>
</ScrollViewer>
</ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
委托命令:
public class DelegateCommand : ICommand
{
private readonly Action _command;
private readonly Func<bool> _canExecute;
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public DelegateCommand(Action command, Func<bool> canExecute = null)
{
if (command == null)
throw new ArgumentNullException();
_canExecute = canExecute;
_command = command;
}
public void Execute(object parameter)
{
_command();
}
public bool CanExecute(object parameter)
{
return _canExecute == null || _canExecute();
}
}
指令:
public ICommand OpenSessionCommand { get
{ return new DelegateCommand(OpenSession); }
}
public void OpenSession()
{
ContinueReceiving = false;
dispatcherTimer.Stop();
Messenger.Default.Send<NavigateMessage>(
new NavigateMessage(SessionViewModel.ViewName, this));
}