开发者

Listbox of buttons and relative source

I have a listbox bound to a view model property called Choices. Each choice has a label and an index. I need to bind the buttons in the list to a command on the same view model. So far Ive figured out this much:

<ListBox Grid.Row="1" ItemsSource="{Binding Choices}" SelectedIndex="{Binding SelectedChoice, Mode=TwoWay}"开发者_如何学Python >
  <ListBox.ItemTemplate>
    <DataTemplate>
      <Grid HorizontalAlignment="Stretch" Margin="1">
        <Button Content="{Binding Caption}" Height="24" HorizontalAlignment="Stretch" 
                Command="{Binding RelativeSource={RelativeSource ???}, 
                                  Path=SelectChoice}" CommandParameter="{Binding}"/>
      </Grid>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

I cant figure out what RelativeSource to use for the command and I'm not sure the CommandParameter is correct.

This seems a really simple thing to do but it's obviously too simple for my poor old brain. Can anyone help please?

Thanks


Sorted:

    <ItemsControl Grid.Row="1" ItemsSource="{Binding Choices}" >
  <ItemsControl.ItemsPanel >
    <ItemsPanelTemplate >
      <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
      </StackPanel>
    </ItemsPanelTemplate>
  </ItemsControl.ItemsPanel>
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <Button Content="{Binding Caption}" Height="24" HorizontalAlignment="Stretch" Margin="0,0,4,0"
              Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ItemsControl}}, Path=DataContext.SelectChoice}" 
              CommandParameter="{Binding}"/>
    </DataTemplate>
  </ItemsControl.ItemTemplate>
</ItemsControl>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜