標題幾乎總結了它。我一直試圖使用按鈕的CommandParameter,但我不知道它應該是什麼,以及我需要在ViewModel類中添加哪些代碼。任何幫助,將不勝感激。如何將當前選定的ListView對象項返回到ViewModel的按鈕單擊
XAML:
<ItemsControl>
<StackPanel Orientation="Horizontal">
<Button Command="{Binding ButtonClick}" Width="150" Margin="5" Height="22" HorizontalAlignment="Left">Click</Button>
</StackPanel>
<ListView Name="listView" Grid.Row="1" BorderThickness="0" ItemsSource="{Binding myObjects}">
<ListView.View>
<GridView>
<GridViewColumn Header="Space ID" DisplayMemberBinding="{Binding ID}" Width="Auto" />
</GridView>
</ListView.View>
</ListView>
</ItemsControl>
視圖模型C#:
public ICommand ButtonClick
{
get { return new DelegateCommand(BtnClick); }
}
private void BtnClick()
{
//Access selected object of type myObject here.
}
DelegateCommand類:
public class DelegateCommand : ICommand
{
private readonly Action _action;
public DelegateCommand(Action action)
{
_action = action;
}
public void Execute(object parameter)
{
_action();
}
public bool CanExecute(object parameter)
{
return true;
}
}