开发者

Listbox of buttons and relative source

开发者 https://www.devze.com 2023-01-29 02:06 出处:网络
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 th

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

精彩评论

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

关注公众号