ListBox 绑定之-SelectedItem

注意<i:Interaction>需要使用Blend的System.Windows.Interactivity.dll文件。

通过<i:Interaction.Triggers> 关联到SelectionChanged事件,当前台获取到SelectedItem时,就会调用ViewModel的ExecuteGetItem方法,获取选择项。

XAML:

<ListBox ItemsSource="{Binding StandardSet,Mode=TwoWay}" SelectionMode="Single" Name="lb_items"
  Margin="0,0,0,125"
  >
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="SelectionChanged">
    <i:InvokeCommandAction Command="{Binding GetItemCommand}"
      CommandParameter="{Binding ElementName=lb_items}"></i:InvokeCommandAction>
    </i:EventTrigger>
  </i:Interaction.Triggers>
  <ListBox.ItemsPanel>
    <ItemsPanelTemplate>
      <WrapPanel ItemHeight="30" ItemWidth="100"></WrapPanel>
    </ItemsPanelTemplate>
  </ListBox.ItemsPanel>
  <ListBox.ItemTemplate>
    <DataTemplate>
      <ListBoxItem Content="{Binding Path=Standard.Name}"
        IsSelected="{Binding Path=IsSelected,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
        >
      </ListBoxItem>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

ViewModel:

public DelegateCommand<ListBox> GetItemCommand { get; set; }

public void ExecuteGetItem(ListBox lb)
{
  StandardViewModel model = lb.SelectedItem as StandardViewModel;
}

原文地址:https://www.cnblogs.com/gnsds/p/3664746.html